noHistory vs finish() - Which is preferred?

你说的曾经没有我的故事 提交于 2019-12-03 05:36:00

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.

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.

Harshal Benake

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"/>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!