只有一个IntentService实例

时间:2015-08-28 03:34:16

标签: android android-service android-broadcast android-intentservice

我想设置一个IntentService来手动启动计时器。在创建新数据的情况下,我想“手动”触发IntentService以立即发送数据。计时器将每隔几分钟运行一次,以确保所有数据都已被发送,如果没有,它将发送数据。

有没有办法阻止/锁定IntentService,这样如果我已经手动发送数据并且计时器触发服务,则不会尝试两次提交相同的数据?

我有以下IntentService,它会将一个项目从数据库中拉出来并将该信息发布到服务器。

public class MyBroadcastReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
       //Grab stuff I care about
       Long someId = ....;

       Intent i = new Intent(context, MyIntentService.class);
       i.putExtra(SERVICE_ID, someId);
       context.startService(i);
    }
}

我有一个BroadcastReceiver,每隔一段时间就会启动一次,以启动该意向服务:

AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
intent = new Intent(getApplicationContext(), MyBroadcastReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1001, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 60 * 10, pendingIntent);

我启动广播接收器,每10分钟发射一次

// On some event happened manually start intent (not on timer)
Context context = getApplicationContext();
Intent intent = new Intent(context, MyIntentService.class);
intent.putExtra(SERVICE_ID, someId);
context.startService(intent);

当我有新的数据要发送时,我会根据事件在代码中的其他地方手动触发

BLS.GOV

我能否以某种方式阻止以确保没有多个MyIntentServices同时运行,这可能会发送相同的数据?

0 个答案:

没有答案