问题
I have problem with Alarm Manager. I create alarm manager which repeat displaying toast every 15 seconds.
After rebooting my device, toast is visible, but only once. I want to repeat it again every 15 seconds even after reboot.
What can I add to solve this? Is this possible?
Here is my code (class AlarmReceiver extends 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);
}
And my 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>
EDIT: The solve of this problem is edit code in 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);
}
}
回答1:
It seems like you simply need to call your SetAlarm function in the onReceive Method, and listen for the sent event in your manifest.
In your manifest
<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>
As your intent
Intent intent = new Intent();
intent.setAction("com.packagename.custombroadcast");
//Use Context.sendBroadcast
sendBroadcast(intent);
来源:https://stackoverflow.com/questions/25650693/alarm-manager-isnt-repeating-after-reboot