Issue when app coming back to foreground

心不动则不痛 提交于 2019-12-04 08:45:42

A dirty workaround to your problem is to check if the global variables are filled in the onResume method of your activities. If the variables are not filled start the splashscreen activity with an Intent with the CLEAR_TOP flag set. This should cause all your activities to be removed from the activity stack and your splash screen will load and is able to reload all the data needed for your app to work.

This is a dirty workaround to help a badly designed application to work. If you want your app to be nicer to you and the user go with the solution inazaruk provided. He is correct about the basic setup of an application.

This is not direct answer to you question, but I thought it might be useful.

Your decision to store data in global variables is bad. That's because your app can be killed each time user navigates away from it. And when he or she comes back you'll need to load data all over again.

You should use ContentProvider and Service. Service should load data from internet and store it to ContentProvider. ContentProvider should persist data. All activities should use ContentProvider to access this cached data.

This way your application:

  1. Will not need to download data every time application is started (saving CPU, battery and bandwidth)
  2. Your activities can rely on the fact that there is cached data in ContentProvider.
  3. Every time data is update in ContentProvider, each Activity can be notified and update UI.
  4. Data in ContentProvider is persisted across application runs (if you use SQLite for example).
  5. Background service that reads data from web-service and syncs it with ContentProvider is completely decoupled from Activities.

Of cause you need to invest some time into implementing Service and ContentProvider, and proper handling in Acitivities. But your application will be more robust and scalable (you can easily add new components).

When android kills your application, it is doing so only to save resources. In order to have a better usability, the OS will remember where you were inside that app (saving things like the activity stack a instance state if you implement the proper listeners).

When you restore your app, it will restore the activities and everything else. As you were saving data to global static variables, these might have been "lost" when the application was terminated!

I suggest you to use databases or at least check if the data is still there before using it (for example: MyClassHolder.myGlobalStaticParameter == null)

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