Run Code When Android App Is Closed/Sent to Background

Run code when Android app is closed/sent to background

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

Android: Run code when application is permanently closed

you need to add a background service

public class BackgroundServices  extends Service
{

@Override
public void onCreate() {
Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

}

@Nullable
@Override
public IBinder onBind(Intent intent) {

return null;
}

@Override
public void onDestroy() {

super.onDestroy();
}
}

then in your activity. where you want to trigger this service

use

 startService(new Intent(getBaseContext(), BackgroundServices.class));

in your case it will be call on onDestory function of that activity

How to execute background task when Android app is closed / set to background?

The following code will help you to post your contents when your app is closed or in the background:

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

public class SendDataService extends Service {
private final LocalBinder mBinder = new LocalBinder();
protected Handler handler;
protected Toast mToast;

public class LocalBinder extends Binder {
public SendDataService getService() {
return SendDataService .this;
}
}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

@Override
public void onCreate() {
super.onCreate();

}

@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {

// write your code to post content on server
}
});
return android.app.Service.START_STICKY;
}

}

More explanation of my code is:

Service runs in the background even if your application is in the background, but remember, it always runs on the main thread, because of which I created a separate thread to perform your background operations.

Service is started as a sticky one, as even if because of any reason your service got destroyed in the background it will automatically get restarted.

More details can be found here:
https://developer.android.com/guide/components/services.html

And to check if your app is in the foreground/background, the following code will help:

  private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}

// Use like this:
boolean foregroud = new ForegroundCheckTask().execute(context).get();

Happy Coding!!!!

How to detect when an Android app goes to the background and come back to the foreground

The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed. You can read more in Activity.

There isn't any direct approach to get the application status while in the background or foreground, but even I have faced this issue and found the solution with onWindowFocusChanged and onStop.

For more details check here Android: Solution to detect when an Android app goes to the background and come back to the foreground without getRunningTasks or getRunningAppProcesses.

How do I run a counter when the app is closed or sent to the background?

You do not need to set a timer when your app is closed. And you cannot set a timer because it will get destroyed when app closes.

You simply need to get the system time like this

long time = System.currentTimeMillis();

Store this current system time in shared preferences when user exits.
And when the user comes back online get the savedTime from preferences and compare with freshly fetched currentTime.

long currentTime = System.currentTimeMillis();

long elapsedTime = currentTime - savedTime;


Related Topics



Leave a reply



Submit