Вопрос

I've various options to sync data between android app and server. I'm using AlarmManager to trigger sync with user choices. I've one which says Never Update (Update Manually) in which i cancel with toStopServiceAlarm() the AlarmManager.

Que:

It's working fine as long as my application won't be killed by any task manager. As soon as it's killed by Task Manager application service again started with Never Update(Update Manually) where i already cancelled any AlarmManager trigger.

Can anybody help me in preserving my application behaviour even if it's killed by Task Manager? Sync get called as per user choice only.

Code Snippet:-

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);
 }
}
Это было полезно?

Решение

As per CommonsWare, I just need to override onStartCommand() with START_NOT_STICKY which will make my service loosly tight with Android and won't start once it's killed by TaskManager. That's what behaviour expected from that running Service.

Code Snippet:

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;
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top