问题
I don't want my application to show few Activity
(say SplashScreenActivity
) when pressing back
button. So I've used noHistory=true
in my Manifest.xml
for that Activity
as show below:
<activity
android:name="com.gokul.SplashScreenActivity"
android:noHistory="true" >
</activity>
Instead of setting noHistory
, I can also call finish()
in my SplashActivity.onPause()
method or wherever I want, as shown below:
@Override
protected void onPause() {
super.onPause();
finish();
}
Both does the job perfectly. But which one is better to use, to use noHistory
or call finish()
?
回答1:
onPause()
is not at all a good place to put a finish()
call for your activity. onPause()
can be called for a variety of reasons, and I doubt your users would be very pleased to see that whatever they were doing was simply forgotten by your app if they, for instance, turn the screen off and back on.
noHistory
should serve you just fine, but you can get a similar behavior by calling finish()
in your Activity
immediately after it launches a new Activity
. However, noHistory
is more maintainable in the end, because you may end up forgetting to include the finish()
call if you add another startActivity()
call to your SplashActivity
later.
回答2:
If you want to call finish()
, you should do it after a startActivity
call, if you do it in any of the lifecycle callbacks, as NasaGeek says, it could be called in diferent moments, and not only when navigating to other activity.
The good thing of noHistory
, is that the system takes care of finising the activity in the correct moment (as you can read here, the system will actually call the finish() method for you) so you can be sure that you are not calling it in a bad moment, and everything is safe (probably this doesn't seem important now, but it could be, for instance when working with threads)
Also, the good thing of it, is that the activity is not only finished when you launch another activity, but also in any other case when the user navigates away from it and the activity no longer visible on screen, for instance when the user press the back button (as you wanted) or when another activity comes to the foreground.
回答3:
Don't use onPause() as is called when the activity goes in the background. And this case can be anytime such as on intent or popup message(custom). It's better to use another option rather playing with the life cycle of the activity. nohistory option if it works for you then it is nice. You can try following also,
<activity
android:name="com.gokul.SplashScreenActivity"
android:launchMode="singleTask"
android:clearTaskOnLaunch="true"/>
回答4:
When you use noHistory, there could be some weird issues when you ask for permissions on that activity.
On Samsung Galaxy S5(Android 6), the activity is closed when the permissions dialog is displayed
来源:https://stackoverflow.com/questions/21374897/nohistory-vs-finish-which-is-preferred