【问题标题】:Android background service never starts when killed app from recent task list从最近的任务列表中杀死应用程序时,Android 后台服务永远不会启动
【发布时间】:2017-03-31 14:04:43
【问题描述】:

我想在 Android 中创建一个永无止境的后台服务。为此,我使用 AlarmManager 和 Simple 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 方法,但服务仍然没有重新开始。

也正如人们所说,从onStartCommand()返回START_STICKY 这样,即使由于资源限制而必须停止服务,系统也会重新启动服务。

在清单文件的&lt;service&gt; 标记中也使用了"stopWithTask"=false。它也没有任何影响。

【问题讨论】:

    标签: android service broadcastreceiver


    【解决方案1】:

    我已经成功地通过警报管理器创建了一个 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 类中以编程方式初始化接收器。在清单中创建意图时,它似乎不起作用。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多