I have an Android application which sends some data to a webservice. I need to send this data as soon as the application is closed or sent to background.. But how do I accomplish this?
My current solution is to run it on the OnPause() on my home activity, but I need this to run no matter which activity the user is on when closing the app.. Is this possible or do I have to add the OnPause method to all activities?
In order to make Android allow apps to run in background, all you need to do is press the open padlock icon right next to them. Once the open padlock changes and you get the “Locked” pop-up notification on your screen, you're all set!
The onPause and onResume are Activity specific. Not Application. When an App is put on background and then resumed, it resumes the specific Activity it was in before going to background. This means that you would need to implement whatever you want done on resuming from background in all Activity of your Application.
onStart() It is invoked when the activity is visible to the user. It is followed by onResume() if the activity is invoked from the background. It is also invoked after onCreate() when the activity is first started.
Check this solution first https://stackoverflow.com/a/5862048/1037294 before you decide to use the code below!
To check if your application is sent to background, you can call this code on onPause()
or onStop()
on every activity in your application:
/** * Checks if the application is being sent in the background (i.e behind * another application's Activity). * * @param context the context * @return <code>true</code> if another application will be above this one. */ public static boolean isApplicationSentToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }
For this to work you should include this in your AndroidManifest.xml
<uses-permission android:name="android.permission.GET_TASKS" />
Edit
This answer only serves for one purpose, that is, running a code in onPause()
for all activities. It doesn't let you run a code when your app is sent to background.
Original Answer
Make an Activity named YourBasicActivity
and override its onPause()
method and extend every Activity from YourBasicActivity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With