我需要每天更新我的应用程序的接口,并使用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,但它不是从onReceiver的BroadcastReceiver方法开始的。我的服务:
<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)。
答案 0 :(得分:1)
每次客户端明确启动服务时由系统调用 通过调用startService(Intent),提供它提供的参数 以及表示开始请求的唯一整数标记。不要打电话 这个方法直接。
如果你打电话,那么这是首选方式:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
return START_REDELIVER_INTENT;
}