Stop service on swipe to remove

泄露秘密 提交于 2020-01-05 20:55:14

问题


App killed from Recently open application list by swipe.

In my application,
I am running service in background only when application is available in foreground or in background. If user has sent application in background by pressing home button of mobile then also service should be run.


But when user remove application from recently opened application then
1) Is any methods invoke automatically when removed from recent app list?
2) Which method will be invoke?

  • My Requirement:
    when application going to remove from recently open application at that time i will stop service which is already running in backgound.

    • Issue Faced:
      1) I have N number of activities...
      2) I also want to know you that when application going to remove from recent list. Android OS not called onDestroy() method even . Activities which is in activity stack.

回答1:


1.You can stop the service in the activities onDestroy method.

2.or In the manifest file, you can also add stopwithtask=true

<service 
    android:name="com.mycompany.TestService"
    android:stopWithTask="true" 
  />

3.or You could also check whether 'onTaskRemoved' is invoked.onTaskRemoved doc




回答2:


public boolean isAppRunning()
    {
        boolean appFound = false;
        final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

        for (RunningTaskInfo recentTask : recentTasks)
        {

            if (recentTask.baseActivity.getPackageName().equals("your.packagename"))
            {
                appFound = true;
                break;
            }

        }
        return appFound;
    }

using this method i have solved my problem if i got false then i will close my service.

need to add permission:

<uses-permission android:name="android.permission.GET_TASKS" />

Hope its worked




回答3:


You should Add the permission in you manifets

 Like: android:excludeFromRecents="true"

 Code:<activity
        android:excludeFromRecents="true"
        android:name="Example.com.MainActivity"
        android:label="@string/app_name" >
          <intent-filter>
             <action android:name="android.intent.action.MAIN" />                       
             <category android:name="android.intent.category.LAUNCHER"/>
         </intent-filter>
      </activity>


来源:https://stackoverflow.com/questions/24163541/stop-service-on-swipe-to-remove

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