我有一个AlarmManager
在BroadcastReceiver
子类中设置,使用Service
子类作为上下文。 AlarmManager
没有被解雇。我知道AlarmManager
正在设置正确的毫秒数。
为什么AlarmManager没有触发的任何想法?
public class Alarm extends BroadcastReceiver
{
public static final String TAG = "Alarm";
public MediaPlayer mediaPlayer;
public AlarmManager alarmManager;
@Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "Alarm set off onReceive");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//Put to code to execute upon alarm here
//Check to see if the sounds are playing, if they are stop them.
if (mediaPlayer.isPlaying()){
//Call play will simulate the user tapping the play button which will stop the sounds.
mediaPlayer.stop();
mediaPlayer.release();
}
wl.release();
}
public void setAlarm(Context context, long milliSeconds, MediaPlayer mp)
{
//Set the mediaPlayer member var
mediaPlayer = mp;
//Figure out the time to stop the timer in milliseconds
long currentTime = System.currentTimeMillis();
long timeToSetAlarmTo = currentTime+milliSeconds;
Log.d(TAG, "Current Time = " + currentTime + "Time to add = " + milliSeconds + "Time to set timer to = " + timeToSetAlarmTo);
//Create the intent
Intent i = new Intent("SmartlifeSoftware.START_ALARM");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, i, 0);
//Set the alarm
alarmManager=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToSetAlarmTo, pendingIntent);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent("SmartlifeSoftware.START_ALARM");
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(sender);
}
}
以下是应用程序标记
下的清单代码 <receiver android:name="services.Alarm" android:exported="true">
<intent-filter>
<action android:name="SmartlifeSoftware.START_ALARM">
</action>
</intent-filter>
</receiver>`
答案 0 :(得分:0)
我解决了这个问题。在alarmManager.set
方法中,我将int type
参数从AlarmManager.ELAPSED_REALTIME_WAKEUP
更改为AlarmManager.RTC_WAKEUP
。 RTC_WAKEUP
指定开火时间。
来自文档:
RTC_WAKEUP
- 唤醒设备以在指定时间触发待处理的意图。
ELAPSED_REALTIME_WAKEUP
- SystemClock.elapsedRealtime()中的闹钟时间(启动后的时间,包括睡眠时间),它会在设备熄灭时唤醒设备。
答案 1 :(得分:0)
由于您的triggerAtMilis参数错误,您的闹钟不会因AlarmManager.ELAPSED_REALTIME_WAKEUP而触发。你应该改变:
long currentTime = System.currentTimeMillis();
long timeToSetAlarmTo = currentTime+milliSeconds;
到
long currentTime = SystemClock.elapsedRealtime()
long timeToSetAlarmTo = currentTime+milliSeconds;