How can i check if my app is running

2020-05-02 05:56发布

问题:

  1. How can i check if my android app is already running to prevent double launch?

  2. How can i make "hard exit" to prevent my app running on background?

回答1:

  1. It is not possible to have "double launch". If you application is running already, if you try to launch another instance, than you'll resume the first launch instance.

  2. You can finish activity by adding .finish() in all scenarios when application can be in onPaused() sequence of the lifecycle or add finish() in onPaused()



回答2:

This may help you

ActivityManager activityManager =(ActivityManager)gpsService.this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList= activityManager.getRunningServices(Integer.MAX_VALUE);

if((serviceList.size() > 0)) {
    boolean found = false;

    for(int i = 0; i < serviceList.size(); i++) {
        RunningServiceInfo serviceInfo = serviceList.get(i);
        ComponentName serviceName = serviceInfo.service;

        if(serviceName.getClassName().equals("Packagename.ActivityOrServiceName")) {
            //Your service or activity is running
            found = true;
            break;
        }
    }
    if(found) {
        //Close your app or service
    }
}