我正在重構一些代碼,以便我的應用程序每天在給定時間從一個網站提取數據。從我的研究看來,AlarmManager
似乎是最合適的方法。AlarmManager,BroadcastReceiver和服務不工作
我一直在下面的教程:http://mobile.tutsplus.com/tutorials/android/android-fundamentals-downloading-data-with-services/
到目前爲止,AlarmManager
和BroadcastReceiver
似乎工作,但是Service
似乎永遠不會啓動(即onStartCommand
似乎不叫)
這裏是代碼的重要片斷我到目前爲止:
MyActivity.java
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.setTimeZone(TimeZone.getDefault());
updateTime.set(Calendar.HOUR_OF_DAY, 20);
updateTime.set(Calendar.MINUTE, 30);
Intent downloader = new Intent(context, AlarmReceiver.class);
downloader.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// should be AlarmManager.INTERVAL_DAY (but changed to 15min for testing)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
Log.d("MyActivity", "Set alarmManager.setRepeating to: " + updateTime.getTime().toLocaleString());
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, MyService.class);
context.startService(dailyUpdater);
Log.d("AlarmReceiver", "Called context.startService from AlarmReceiver.onReceive");
}
}
MyService.java
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "About to execute MyTask");
new MyTask().execute();
return Service.START_FLAG_REDELIVERY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class MyTask extends AsyncTask<String, Void, boolean> {
@Override
protected boolean doInBackground(String... strings) {
Log.d("MyService - MyTask", "Calling doInBackground within MyTask");
return false;
}
}
}
AndroidManifest.xml中
<application ...>
...
<service android:name="MyService"></service>
<receiver android:name="AlarmReceiver"></receiver>
</application>
當我TR igger 中的setRecurringAlarm
日誌打印如下,同樣,每15分鐘從AlarmReceiver
出現日誌。但是,我從來沒有看到日誌從我在日誌中看到MyService
:(
例子:
DEBUG/MyActivity(688): Set alarmManager.setRepeating to: Jan 29, 2012 8:30:06 PM
DEBUG/AlarmReceiver(688): Called context.startService from AlarmReceiver.onReceive
DEBUG/AlarmReceiver(688): Called context.startService from AlarmReceiver.onReceive
似乎無法找出我錯了做 - 從Android Dev Docs我的理解在AlarmReceiver
當我打電話context.startService(dailyUpdater)
,在依次調用onStartCommand
在MyService
,雖然這似乎是應該不會是這樣!
我在做什麼錯,是造成MyService
無法啓動呢?
+1感謝您的代碼,幫助我.. – Nirali 2012-06-15 12:09:42
你也運行到響應警報啓動服務的非顯而易見激活鎖定行爲。有一些細節和建議的答案在http://stackoverflow.com/questions/25852309/does-alarmmanager-require-the-pendingintent-to-be-of-type-broadcastreceiver – ctate 2014-09-15 23:24:50