问题
Scenario :
I open my app by clicking icon, do something, navigate through activities, pause the app by clicking home button.
Case 1:
If I open my app by clicking icon again, the app restarts from the first activity.
Case 2:
If I open my app from recently open apps (in 4.0 by pressing menu button and selecting my app) it starts from the paused state.
I want the behavior 2 always to occur, don't want my app to restart every time when it is opened by clicking icon.
I have compared my manifest file with other apps and they are similar to mine, but behave differently (i.e like 2nd case which i want).
Edit:
This has been asked here : App completely restarting when launched by icon press in launcher
but no answers :(
回答1:
I found it. I had set a flag android:launchMode="singleTask"
in my activity flag. I deleted that code.
I also added onsaveInstance
method to all the activities in my code and it's working now!
Thanks :)
回答2:
Add this to your launcher activity:
if (!isTaskRoot()) {
finish();
return;
}
super.onCreate(savedInstanceState);
回答3:
In current activity set some image which needs to be displayed for 2 seconds like below.
ImageView im = new ImageView(this);
im.setImageResource(set your image);
setContentView(im);
intentMainScreen = new Intent(getApplicationContext(), MainScreen.class);
Handler x = new Handler();
x.postDelayed(new splashhandler(), 2000);
Then start your activity in the SplashHandler class (which implements runnable and call start activity in run method).
It will display your Splash screen for 2 seconds and start another activity.
回答4:
Try to replace you splash Activity code with this code..
public class Splash extends Activity {
protected boolean _active = true;
protected int _splashTime = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread splashTread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while (_active && (waited < _splashTime)) {
sleep(100);
if (_active) {
waited += 100;
}
}
} catch (InterruptedException e) {
e.toString();
} finally {
Intent intent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(intent);
finish();
}
}
};
splashTread.start();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
// super.onBackPressed();
}
}
来源:https://stackoverflow.com/questions/17545924/android-app-restarts-when-opened-by-clicking-app-icon