使用服务发送Android池数据

时间:2014-06-14 07:45:55

标签: android background-process

我有一个应用程序,它将向网络API发送100个数据。现在我正在使用一个将通过调度程序运行的服务。我的问题是调度程序在数据发送完成之前再次启动。如何在我的流程完成之前暂停我的调度程序。

 public class PollReceiver extends BroadcastReceiver {
 private static final int PERIOD=100000;
  @Override
  public void onReceive(Context ctxt, Intent i)
  {
scheduleAlarms(ctxt);
  }
  static void scheduleAlarms(Context ctxt)
   {
AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(ctxt, ScheduledService.class);
     PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
     mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime() +     PERIOD, PERIOD, pi);
   }
     }

Schedule Reciever

    public ScheduledService()
    {
    super("ScheduledService");
}

@Override
protected void onHandleIntent(Intent intent) 
     {
    if (isOnline())
            {
        //Process Starts 
    }
}

2 个答案:

答案 0 :(得分:0)

在发送完成后设置新计划。设置第一个计划后,下一个计划由服务本身设置:

public class PollReceiver extends BroadcastReceiver {
    private static final int PERIOD=100000;

    @Override
    public void onReceive(Context ctxt, Intent i)
    {
            scheduleNextAlarm(ctxt);
    }

    static void scheduleNextAlarm(Context c)
    {
        AlarmManager mgr=(AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(c, ScheduledService.class);
        PendingIntent pi=PendingIntent.getService(c, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        mgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + PERIOD, pi);
    }

    public static class ScheduledService extends IntentService{

        public ScheduledService() {
            super("scheduled_service");
        }


        @Override
        protected void onHandleIntent(Intent intent) {
            try{
            // do your work
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                scheduleNextAlarm(this);
            }
        }
    }
}

答案 1 :(得分:0)

同志,从你的代码中我看不出你是如何执行这个hudnread请求的,它每个时段只显示一个请求。

我建议的是每个时段调用serviceservice使用队列进行操作。当你调用service时,你调用它的相同实例,所以在完成前期任务之前调用它应该不是问题。

顺便提一下几句话:

  • service不创建线程,以避免ANR例外 必须自己创建线程
  • IntenService创建线程和 而且IntentSrevice在队列中逐个处理意图 - 它 似乎你需要什么
  • 您可以实施SerializableParcelable 用于将执行包装到API并在intent中传递的类 或存储在磁盘上