Android 服务在被任务管理器终止后再次启动

Android 服务在被任务管理器终止后再次启动,android,android-service,android-alarms,Android,Android Service,Android Alarms,我有各种选项可以在android应用程序和服务器之间同步数据。我正在使用AlarmManager触发与用户选择的同步。我有一句话是说从不更新(手动更新),我用toStopServiceAlarm()取消了AlarmManager 奎: 只要我的应用程序不会被任何任务管理器杀死,它就可以正常工作。一旦它被任务管理器杀死,应用程序服务将再次从从不更新(手动更新)启动,我已经取消了任何AlarmManager触发器 有人能帮我保存我的应用程序行为吗,即使它被任务管理器杀死了?仅根据用户选择调用同步 代

我有各种选项可以在android应用程序和服务器之间同步数据。我正在使用
AlarmManager
触发与用户选择的同步。我有一句话是说
从不更新(手动更新)
,我用
toStopServiceAlarm()
取消了
AlarmManager

奎: 只要我的应用程序不会被任何任务管理器杀死,它就可以正常工作。一旦它被任务管理器杀死,应用程序服务将再次从
从不更新(手动更新)
启动,我已经取消了任何
AlarmManager
触发器

有人能帮我保存我的应用程序行为吗,即使它被任务管理器杀死了?仅根据用户选择调用同步

代码段:-

public class ServiceAlarm extends WakefulBroadcastReceiver {

public void onReceive(Context context, Intent intent) {  
Intent service = new Intent(context, UploadData.class); //UploadData is my service
    startWakefulService(context, service);
}

public void startServiceAlarm(String times)
{
 context = SmartConsultant.getApplication().getApplicationContext();
 alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);      
 Intent intent = new Intent(SmartConsultant.getApplication().getApplicationContext(), UploadData.class);
 alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

 Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(System.currentTimeMillis());
 calendar.set(Calendar.HOUR_OF_DAY, 21);
 calendar.set(Calendar.MINUTE, 00);

 switch(Integer.parseInt(times))
 {
  case 0://midnight
            alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
  break;
  ... cases for different interval of sync
 }
}

public void toStopServiceAlarm(String times)
{
   if (alarmMgr != null) {
  alarmMgr.cancel(alarmIntent);
 }
}

根据Commonware,我只需要用
START\u NOT\u STICKY
覆盖
onStartCommand()
,这将使我的服务在Android上非常紧凑,一旦被
TaskManager
杀死就不会启动。这就是运行
服务所期望的行为

代码段:

public class UploadData extends Service
{
...
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    super.onStartCommand(intent, flags, startId);
    return START_NOT_STICKY;
    }
}

你的问题很可能在于你的服务。如果
onStartCommand()
返回类似
START\u STICKY
START\u REDELIVER\u INTENT
的内容,则会重新启动服务,这是
IntentService
的默认行为。您可以在
IntentService
onCreate()
中调用
setIntentRedelivery(false)
来禁用此功能。@commonware我的服务
扩展服务
。我没有覆盖服务中的
onStartCommand
。因此,我是否应该在onCreate()中包含
setIntentRedelivery(false)
“我是否应该在onCreate()中包含setIntentRedelivery(false)?”——如果您将服务更改为扩展
IntentService
,则是。否则,从
onStartCommand()
返回
START\u NOT\u STICKY
。另外,请确保您在某个时间点停止服务,同时释放
WakeLock
。@commonware:谢谢!按预期工作!