How to determine app is running from service

房东的猫 提交于 2019-12-10 17:06:40

问题


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.



来源:https://stackoverflow.com/questions/13858526/how-to-determine-app-is-running-from-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!