我需要每天更新我的应用程序的内容,为此我使用 AlarmManager、BroadcastReceiver 和 IntentService。
我在从 Application 类扩展的类中创建 AlarmManager 对象和 setRepeating:
private void setRecurringAlarm(Context context) {
Intent intent = new Intent(AlarmReceiver.ACTION_ALARM);
AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
1234567, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarms.setRepeating(AlarmManager.RTC,
System.currentTimeMillis(), 10000, pIntent);
Toast.makeText(getApplicationContext(), "started", Toast.LENGTH_SHORT).show();
}
我的 BroadcastReceiver 成功获取消息:
public class AlarmReceiver extends BroadcastReceiver {
private static final String DEBUG_TAG = "AlarmReceiver";
public static String ACTION_ALARM = "com.alarammanager.alaram";
@Override
public void onReceive(Context context, Intent intent) {
Intent downloader = new Intent(context, UpdateService.class);
downloader.setAction(Constants.UPDATE_SERVICE);
context.startService(downloader);
Toast.makeText(context, "Entered", Toast.LENGTH_SHORT).show();
}
}
但是我也需要从BroadcastReceiver启动IntentService,但不是从BroadcastReceiver的onReceiver方法启动。我的服务:
<service android:name="com.services.UpdateService"
android:enabled="true">
<intent-filter>
<action android:name="com.service.UpdateService" />
</intent-filter>
</service>
并为此上课。
public class UpdateService extends IntentService {
public UpdateService() {
super("UpdateService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("UpdateService", "About to execute MyTask");
// new MyTask().execute();
Toast.makeText(getApplicationContext(), "updateService", Toast.LENGTH_SHORT).show();
}
// Sometimes overriding onStartCommand will not call onHandleIntent
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("asdasd", "here..!");
return super.onStartCommand(intent,flags,startId);
}
}
我的问题是为什么不能从 BroadcastReceiver 调用它(IntentService)。