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

标签 android service

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

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); 
}

最佳答案

您可以通过监听时间变化的 Broadcast 来克服这个问题。执行以下操作:-

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

<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

也是一个很好的教程

关于android - 更改系统时钟时警报管理器停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21985529/

相关文章:

c# - Xamarin.Forms 微调器 TimePicker

android - 无法调试库项目

java - Kryonet RMI 抛出异常 => 循环 (StackOverflowError)

service - 什么是分布式锁服务器

C++ 服务示例 - Unicode 转换

android - 我正在尝试从服务启动 Activity ,但应用程序正在强制关闭。我正在从广播接收器启动服务

Android BottomSheetDialog 布局有按钮,onclick 导航到 Activity

java - 解密期间填充 block 损坏(Android)

android - 在 Azure DevOps 中共享版本信息

java - bindservice 不会启动服务并且 onserviceconnect 不会调用