0

我需要按时间间隔运行一项服务,例如每 2 分钟一次。我使用 AlarmManager 注册它,当服务在 2 分钟结束之前自行停止时它工作正常,但很有可能需要超过 2 分钟,在这种情况下,我需要终止服务并启动一个新的,我该怎么做?

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(getApplicationContext(), Sender.class);
    PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, i, 0);  
    am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000 * 30, pi);
4

3 回答 3

1

AlarmManager而不是通过使用广播来启动服务。设置AlarmManager发送一些广播意图。创建您自己BroadcastReceiver的将接收该意图并在onReceive方法中重新启动(停止和启动)服务。

//Start AlarmManager sending broadcast
Intent intent = new Intent(context, MyBroadcastReceiver.class); // explicit
peningIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30 * 1000, pendingIntent);

.

//BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) { 

        Intent serviceIntent = new Intent(SynchronizationService.class.getName());

        context.stopService(serviceIntent);

        context.startService(serviceIntent);
    }
}

.

//Register receiver in AndroidManifest.xml in Application tag
<receiver     
    android:name="com.example.MyBroadcastReceiver" >
</receiver>
于 2013-08-26T11:54:10.057 回答
0

您应该在 onStartCommand 本身中编写登录信息。检查服务是否正在运行或不使用变量。如果它在服务上运行调用 stopSelf 方法,则再次为同一服务调用 startservice。

于 2013-08-26T12:22:44.733 回答
0

启动警报管理器服务,您必须使用此代码

Intent intent = new Intent(activity.this,Sender.class);
pendingIntent = PendingIntent.getBroadcast(activity.this.getApplicationContext(),1, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000 * 30, pendingIntent);

停止此广播接收器使用此代码

Intent intent = new Intent(activity.this,Sender.class);
pendingIntent = PendingIntent.getBroadcast(activity.this.getApplicationContext(), 1,intent, 0);
pendingIntent.cancel() ;
于 2013-08-26T12:31:04.487 回答