How do I check if I am pausing or exiting the appl

2019-08-08 02:34发布

I am currently writing an app for android that i need to start the service when I exit or pause the application. What should i do? In my application, every time when I click a thing, it will go to another activity, so i cannot put the startservice to the onpause inside those activity. What should I do?

4条回答
聊天终结者
2楼-- · 2019-08-08 03:11

Have a look at the Activity life cycle here: http://developer.android.com/reference/android/app/Activity.html

Android doesn't exit the activity when you start a new one, it just pauses it. So starting the service inside onPause() should be fine.

查看更多
叼着烟拽天下
3楼-- · 2019-08-08 03:12

According to android life cycle, onPause() method will call as a first indication that user is leaving your activity. It may leave or not. So as per your requirement you can startService. But make sure don't put heavy code inside as it may effect user experience.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-08-08 03:16

When Activity is no longer visible, it calls onStop(). But still we can not be sure if app is destroyed as Android OS internally handles it. So try following steps to find if you app is in background:

  1. Get the running task info using

    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    
  2. If tasks list is not empty, check if running taks belongs to your app. If it belongs, then return true to the calling function, where you can start your service ; else return false

     if (!tasks.isEmpty()) {
       ComponentName topActivity = tasks.get(0).topActivity;
      if (!topActivity.getPackageName().equals(context.getPackageName()))
      {
         return true;
      }
    

Edit : This may be helpful : http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses

查看更多
混吃等死
5楼-- · 2019-08-08 03:36

By overriding this methods you can check if your app is onPause or onDestroy

protected void onPause() {
    Log.i("Status", "onPause");
    super.onPause();
}

protected void onDestroy() {
            Log.i("Status", "onDestroy");
    super.onDestroy();
}
查看更多
登录 后发表回答