How to determine app is running from service

2019-06-24 07:24发布

问题:

This is the scenario...

  1. App is opened
  2. User clicks on a button that starts a service.
  3. User presses home key and then long presses home key and clears application from task list.
  4. Service continues to run, although app has closed.

How from the runnning service can I determine whether that app has been killed or not? Is this possible?

回答1:

I think this what you are looking for:

 private boolean isAppRunning() {
    ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningTaskInfo task : manager.getRunningTasks(Integer.MAX_VALUE)) {
        if ("com.example.YourLauncherActivityClassFullName".equals(task.baseActivity.getClassName())) {
            return true;
        }
    }
    return false;
}

The only thing you need to provide is full launcher activity class name of your app.



回答2:

first you should start a service, that should look after particular time that whether your activity is running or not. for that you could use Alarm Manager to check after some time.

To check whether your activity is running or not, you should use,

ArrayList<String> runningactivities = new ArrayList<String>();

    ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE); 

    List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE); 

        for (int i1 = 0; i1 < services.size(); i1++) { 
            runningactivities.add(0,services.get(i1).topActivity.toString());  
        } 

        if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
            Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show(); 

        }


回答3:

In you main (first) activity:

public static boolean isRunning;

@Override

public void onCreate(Bundle savedInstanceState) {

    isRunning = true;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ...
}
@Override

public void finish() {
    isRunning = false;
    super.finish();
}

check isRunning flag in your service.