使用已经运行的AlarmManager启动服务

时间:2013-08-26 11:34:36

标签: android

我需要在时间间隔内运行服务,例如每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);

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

答案 2 :(得分: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() ;