我遇到了Alarm Manager的问题。我创建了警报管理器,每隔15秒重复显示一次吐司。
重新启动设备后,可以看到吐司,但只能看一次。我想在重启后每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);
}
}
答案 0 :(得分: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);