从最近的任务列表中杀死app时,Android后台服务永远不会启动

时间:2017-03-31 14:04:43

标签: android service broadcastreceiver

我想在Android中创建一个永无止境的后台服务。要做到这一点,我使用AlarmManager与简单Service Alarmmanger在一段时间后发送广播,在广播接收器中我正在检查服务是否正在运行,如果运行则不做任何其他操作启动它再次。

我的服务代码是

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;
    }
 }

广播接收器

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");
    }
}

我的宣言:

 <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>

当应用程序处于前台或后台时它工作正常但问题是当我从Android的最近任务列表中移出应用程序时,该应用程序被杀死,因此服务和我的广播接收器永远不能再次启动它?我在Alarmmanger方法中重新安排了onTaskRemoved,但服务仍未重新开始。

同样从START_STICKY返回onStartCommand(),因为人们说,即使必须停止资源限制,系统也会重新启动服务。

还在清单文件的"stopWithTask"=false标记中使用了<service>。它也没有影响。

1 个答案:

答案 0 :(得分:0)

我通过报警管理器创建了一个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);
    }
}

我在Application类中以编程方式初始化接收器。当在清单中创建intent时,它似乎不起作用。

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);

    }
}

然后只是清单中没有意图的接收者

 <receiver android:name="HeartbeatReceiver"/>

这是试验的结果,所以我不确定它为什么会起作用,但是如果我杀了应用程序,它会在下一个警报运行时成功返回。希望有所帮助。