Domanda

I want to distinguish the following use cases:

Case 1: A user stays within the same app and navigates through different activities of the same app.

Case 2: A user navigates out of the app, might just call the home screen of his device or call an activity from some other app.

In Case number 2 I want to refresh some data when my main activity is called again, where in case number 1 that is not necessary. The lifecycle methods onResume() and onStart() are called in both cases, so simply placing my code there is not possible. What can I do? Thanks.

È stato utile?

Soluzione

You'll have to write to a shared preference whenever you issue a navigation command that would take you out of your app and check that shared preference when your main Activity is loaded. To handle the back button case you can override onBackPressed() in your activities and to handle pressing of the home button you can check this blog post: http://nisha113a5.blogspot.com/. If you want to handle the recent apps switcher you can do something similar to the home button method.

Altri suggerimenti

You can use the lifecycle events to detect when you are leaving or entering your app. Here are the rules I have found to work:

  • When the user is entering, onResume is always called (on the activity that will be current)
  • When the user is leaving, onStop is always called (on the current activity)*
  • When the user is moving between activities, onResume is always called on the new activity, and onStop is always called on the old one. The onResume call is always before onStop

*except when pressing the power button (to turn off) where you may only see an onPause call.

More info here: http://www.artificialworlds.net/blog/2015/06/05/detecting-whether-an-android-app-is-stopping-or-starting/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top