2015-03-25 52 views
0

我有一个消耗web服务的asynctask。现在我需要在一个小时内每天执行一次asynctask。 我想要做的是在AlarmManager中调用asynctask的doinbackground事件。我已阅读关于使用AlarmManager的信息,但没有关于在asynctask中使用它的文档。 我该走向正确的方向吗? 任何建议将高度apreciate如何在Alarmmanager内运行asynctask?

+0

为什么不使用[__IntentService__](http://developer.android.com/reference/android/app/IntentService.html)来执行WebService的工作,就像您每天在特定时间执行一次一样。 – Bharatesh 2015-03-25 03:51:23

+0

正如bharat所说,你应该使用'IntentService'而不是'AsyncTask'。您需要创建一个闹钟,在需要的时间发送广播。使用'BroadcastReceiver'来监听广播,然后让它启动'IntentService'。在互联网上有很多代码示例,在这里也是堆栈溢出 - 只是做一些搜索。 – Squonk 2015-03-25 04:01:04

+0

@bharat我很困惑,为什么不使用asynctask,因为文档说它应该用于短操作,因为调用web服务.. – montjoile 2015-03-25 04:56:47

回答

0

第1步:创建一个在一天运行一次的报警管理器。 您可以根据自己的要求设定时间。我在这里设定在早上7点。

int REPEATING_TIME = 24 * 60 * 60 * 1000; 
     Calendar calendar = Calendar.getInstance(); 
     calendar.setTimeInMillis(System.currentTimeMillis()); 
     calendar.set(Calendar.HOUR_OF_DAY, 06); 
     calendar.set(Calendar.MINUTE, 59); 
     calendar.set(Calendar.SECOND, 59); 

     Intent i = new Intent(context, DemoService.class); 
     PendingIntent pi = PendingIntent.getService(context, 
       202, i, 
       PendingIntent.FLAG_CANCEL_CURRENT); 

     AlarmManager alarmManager = (AlarmManager) context 
       .getSystemService(Context.ALARM_SERVICE); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
       calendar.getTimeInMillis(), REPEATING_TIME, pi); 

第2步:创建一个asynctask类并在那里执行后台操作。

public class LoadData extends AsyncTask<String, String, String>{ 

    @Override 
    protected String doInBackground(String... params) { 

     return "response"; 
    } 

} 

第3步:创建一个扩展服务的类。

public class DemoService extends Service { 

     @Override 
     public void onCreate() { 
      super.onCreate(); 

     } 

     @Override 
     public int onStartCommand(Intent intent, int flags, int startId) { 
      new LoadData(){}protected void onPostExecute(String result){ 
// anything you want to perform onPost. 
};}.execute("API URL"); 

      stopSelf(); 
      return super.onStartCommand(intent, flags, startId); 
     } 

     @Override 
     public IBinder onBind(Intent intent) { 
      return null; 
     } 

    } 

希望它能解决您的问题。

+1

在'Service'中使用'AsyncTask'是无意义的练习,AsyncTask被设计为与UI交互(而“Service”没有UI)。简单地使用一个'IntentService'来管理自己的工作线程,并在工作完成时关闭。 – Squonk 2015-03-25 04:03:19

+0

你的观点是对的,但有时我们不需要执行与UI相关的任务。就像我们只是想更新数据库等 – 2015-03-25 04:35:30