更改系统时钟时报警管理器停止

时间:2014-02-24 10:46:58

标签: android service

我有一个在后台运行的服务。我正在使用警报管理器来启动此服务。它工作正常但是当我在我的设备或模拟器中更改系统时钟时,警报管理器会停止。

public void startAzanService() {
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, CheckAzan.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    //repeat the action every 5 secionde
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5000, pintent); 
}

1 个答案:

答案 0 :(得分:2)

您可以通过聆听更改Broadcast的时间来解决此问题。执行以下操作: -

1)在BroadcastReceiver文件中创建Manifest: -

<receiver android:name=".TimeChangeReceiver">
        <intent-filter >
            <action android:name="android.intent.action.TIME_SET"/>
        </intent-filter>
</receiver>

2)创建接收器类: -

public class TimeChangeReceiver extends BroadcastReceiver{

@Override
public void onReceive(final Context arg0, Intent arg1) {
    //Call your Alarm setting code
    Calendar cal = Calendar.getInstance();
    Intent intent = new Intent(this, CheckAzan.class);
    PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    //repeat the action every 5 secionde
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 5000, pintent);
   }
}

*假设您的代码没有任何问题:)

link也是BroadcastReceiver

的优秀教程