【问题标题】:Alarm Manager isn't repeating after reboot重新启动后警报管理器不重复
【发布时间】:2014-09-03 17:54:19
【问题描述】:

我对警报管理器有疑问。我创建了警报管理器,它每 15 秒重复显示吐司。

重启我的设备后,toast 是可见的,但只有一次。即使在重新启动后,我也想每 15 秒再重复一次。

我可以添加什么来解决这个问题?这可能吗?

这是我的代码(AlarmReceiver 类扩展 BroadcastReceiver):

@Override
public void onReceive(Context context, Intent intent) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
    //Acquire the lock
    wl.acquire();

    Toast.makeText(context, "wow", Toast.LENGTH_LONG).show();

    //Release the lock
    wl.release();

}

 public void SetAlarm(Context context)
{
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 15000, pi);
}

还有我的 AndroidManifest.xml

<receiver android:name=".view.activity.AlarmReceiver" android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>

编辑:这个问题的解决方法是在 onReceiver() 中编辑代码:

@Override
public void onReceive(Context context, Intent intent) {
    if(intent.getAction()==null){
        Toast.makeText(context, "lol", Toast.LENGTH_LONG).show();

    } else
    {
        AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent1 = new Intent(context, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent1, 0);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 15000, pi);
    }

}

【问题讨论】:

  • 由于您的警报意图显式调用接收器,因此您不需要自定义操作。只需检查 onReceive() 中的 Intent 操作是否为空。如果是,请展示 Toast;否则调用你的方法来设置闹钟。
  • 工作完美!谢谢!

标签: android broadcastreceiver alarmmanager android-alarms


【解决方案1】:

您似乎只需要在 onReceive 方法中调用您的 SetAlarm 函数,并在清单中侦听已发送的事件。

在您的清单中

<intent-filter>
   <action android:name="android.intent.action.BOOT_COMPLETED" />
   <action android:name="android.intent.action.QUICKBOOT_POWERON" />
   //New
   <action android:name="com.packagename.custombroadcast" />
</intent-filter>

如你所愿

Intent intent = new Intent();
intent.setAction("com.packagename.custombroadcast");
//Use Context.sendBroadcast
sendBroadcast(intent); 

【讨论】:

  • 好的,我想过,但我希望也许会有更好的解决方案来实现这一点。谢谢你的回答;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多