开发者

Restarting an activity just like the user is pressing it for the first time

开发者 https://www.devze.com 2023-02-02 21:58 出处:网络
Hey guys. I\'ve just published my first Android application to show this guy who might hire me for his research, and I\'ve got some good reviews except for one problem - my activity force closes with

Hey guys. I've just published my first Android application to show this guy who might hire me for his research, and I've got some good reviews except for one problem - my activity force closes with my 开发者_JAVA百科current code to restart! I dont have an android phone so I cant test it out. Is there a simple way to just restart an app from the beginning? Apparently it force closes with a null pointer exception with this code:

Intent intent = getIntent();
finish();
startActivity(intent);

which I got from another question.

Please help!! I need to have this fixed

Thanks so much


As also suggested by the previous answer, that's really not how the process lifecycle works. What you can do is take all of your initialization code out of your Activity's onCreate method (including setContentView) and move it to a separate method, e.g. loadUi(). Then when you need to refresh the state, call loadUi() again and it will appear as though you've restarted, it will just be much faster.

If you were really stuck on restarting, you could do it by starting a service and then calling finish(), and having some code in the service launch your activity. You probably don't want to do that, but if you are still determined then take a look at http://developer.android.com/reference/android/app/Service.html and http://developer.android.com/reference/android/content/Context.html#startService%28android.content.Intent%29


Put these three lines in a method of its own and move finish() after startActivity().


I dont have an android phone so I cant test it out.

Use an Android Virtual Device.

Is there a simple way to just restart an app from the beginning?

Go to the Launcher, and restart it! To save yourself clicks, make a shortcut on the homescreen. Apps are not supposed to have 'close' buttons, let alone restart buttons. There are many questions on SO about this. Basically, if the user wants to exit your app, they hit the home button. If you want to re-initialize your app, that is not the way to do it, you'll need to manually reset everything to its initial state, or relaunch another instance of your Activity using the classpath.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号