简体   繁体   English

当最新任务列表中的应用被杀死时,Android后台服务永远不会启动

[英]Android background service never starts when killed app from recent task list

I want to create a never ending background service in Android. 我想在Android中创建一个永无止境的后台服务。 To do this I am using AlarmManager with Simple Service Alarmmanger send broadcast after some interval ,In broadcast Receiver I'm checking wether the service is running, if running then do nothing else start it again . 要做到这一点,我使用AlarmManager用简单的Service Alarmmanger一些时间后发送广播,在广播接收器我检查羯羊服务正在运行,如果运行,那么别的什么也不做再次启动它。

My service code is 我的服务代码是

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
           return null;
    }
    @Override
    public void onCreate() {
        super.onCreate ( );
        Log.e ("My service ", "oncreate");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        scheduleAlarm ();
        super.onTaskRemoved (rootIntent);
    }
     // Setup a recurring alarm every half hour
    public void scheduleAlarm() {
        // Construct an intent that will execute the ServiceAlarmReceiver
        Intent intent = new Intent("com.hmkcode.android.USER_ACTION");
        // Create a PendingIntent to be triggered when the alarm goes off
        final PendingIntent pIntent = PendingIntent.getBroadcast(this, ServiceReceiver.REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Setup periodic alarm every 5 seconds
        long firstMillis = System.currentTimeMillis()+5000; // alarm is set right away
        AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        // First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTCWAKEUP
        // Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
        alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
                6000, pIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

         Log.e ("My Service:", " on Start Command");
          return START_STICKY;
    }
 }

Broadcast Receiver 广播接收器

public class ServiceReceiver extends WakefulBroadcastReceiver {

    public static final int REQUEST_CODE=12355;
    public ServiceReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        // check service  is running or not
        if (isMyServiceRunning (MessageService.class,context)){
            // don nothing

        }
        else {
            // launch the service
            if (isConnectedToInternet (context)) {
                Intent serviceIntent = new Intent (context, MyService.class);
                context.startService (serviceIntent);
            }
        }


        Log.e ("hello","wer are in Receiver" );
       // throw new UnsupportedOperationException ("Not yet implemented");
    }
}

My Manifest: 我的清单:

 <receiver
            android:name=".Services.ServiceReceiver"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">

            <intent-filter>
                <action android:name="com.hmkcode.android.USER_ACTION" />
            </intent-filter>
        </receiver>

        <service
            android:name=".Services.MyService"
            android:enabled="true"
            android:stopWithTask="false"
            android:process=":remote"

        >
        </service>

It worked fine when the app is in foreground or in background but the problem is when I swipe out the app from recent Task list in Android, the app got killed so as the service and My broadcast Receiver never able to start it again? 当应用程序处于前台或后台时,它运行良好,但问题是当我从Android的最新“任务”列表中滑出该应用程序时,该应用程序被杀死,因此该服务和“我的广播接收器”再也无法启动它了? I am rescheduling my Alarmmanger in onTaskRemoved Method, but still the service is not starting again. 我在onTaskRemoved方法中重新安排了我的Alarmmanger ,但该服务仍未重新启动。

Also Return START_STICKY from onStartCommand() as people said With this, system will re-start the service even if it has to be stopped for resources limitations. 就像人们所说的那样,还要从onStartCommand()返回START_STICKY 。这样,即使由于资源限制而不得不停止服务,系统也会重新启动该服务。

Also used "stopWithTask"=false in <service> tag of manifest file. 清单文件的<service>标记中还使用了"stopWithTask"=false It also had no impact. 它也没有影响。

I've had success with creating a PendingIntent through the alarm manager and instantiating it through code instead of declaratively. 我已经成功地通过警报管理器创建了一个PendingIntent,并通过代码而不是声明性地实例化了它。

public class HeartbeatReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        try{
            Log.i(MainService.TAG, "** Heartbeat onReceive **");
            if (!Utility.isMyServiceRunning(context)){
                Log.i(MainService.TAG, "Service is dead. Restarting...");
                context.startService(new Intent(context, MainService.class));
                return;
            }
        }
    }

    public void StartHeartbeat(Context context, int interval) {
        this.CancelHeartbeat(context);
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, HeartbeatReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pi);
    }

    public void CancelHeartbeat(Context context) {
        Intent intent = new Intent(context, HeartbeatReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
}

I initialize the receiver programmatically in the Application class. 我在Application类中以编程方式初始化接收器。 It didn't seem to work when the intent was created in the manifest. 在清单中创建意图时,它似乎不起作用。

public class MainApp extends Application {
    @Override
    public void onCreate(){
        super.onCreate();
        MainService.baseContext = getBaseContext();
        HeartbeatReceiver heartBeat = new HeartbeatReceiver();
        heartBeat.StartHeartbeat(MainService.baseContext, 60 * 1000 * 5);

    }
}

Then just the receiver in the manifest with no intent 然后只是清单中的接收者,没有任何意图

 <receiver android:name="HeartbeatReceiver"/>

This was the result of experimenting so I'm not exactly sure why it works but if I kill the app it comes back successfully when the next alarm runs. 这是实验的结果,所以我不确定它为什么能正常工作,但是如果我终止了该应用程序,则在下一次警报运行时它会成功返回。 Hope that helps. 希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从最近的应用列表中清除应用后,后台服务在android牛轧糖和oreo中停止 - When app clear from recent apps list, background service stopped in android nougat and oreo 从最近的应用程序列表中删除后,Android应用程序进程未终止 - Android app process not killed after removed from recent app list 从android中的最新应用列表中检测到应用被杀死 - Detecting app is being killed from the recent app list in android 从最近的应用程序中删除应用程序时,“前台”服务将被终止 - “foreground” service is killed when App is removed from recent apps Android:如何检测从最近的应用列表中杀死的应用? - Android : How to detect app killed from recent apps list? 在ColorOS上从任务管理器中删除应用程序后,后台服务被杀死 - Background service getting killed on removing the app from task manager on ColorOS 当应用程序从android中的最新应用程序列表中删除时,服务停止 - Service stopped when the app removes from recent apps list in android Android - 即使应用程序被终止或设备重新启动,也可以在后台运行服务 - Android - Run a service in background even when app is killed or device rebooted 当应用切换到后台时,我的Android位置服务被杀死 - My android location service killed when app switched to background Android如何在用户杀死应用程序后继续运行后台服务? - Android How to keep Running the background service when app is killed by user?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM