gpt4 book ai didi

android AlarmManager 没有唤醒手机

转载 作者:IT老高 更新时间:2023-10-28 22:10:53 27 4
gpt4 key购买 nike

我希望在某个时间显示一个 Activity 。为此,我正在使用 AlarmManager。当设备处于唤醒状态时它可以正常工作,但如果它处于 sleep 状态则不会唤醒它。

我设置闹钟的代码:

Calendar alarmTime = Calendar.getInstance();
alarmTime.set(Calendar.HOUR_OF_DAY, alarm.hour);
alarmTime.set(Calendar.MINUTE, alarm.minute);
alarmTime.set(Calendar.SECOND, 0);

if (alarmTime.before(now))
alarmTime.add(Calendar.DAY_OF_MONTH, 1);

Intent intent = new Intent(ctxt, AlarmReceiver.class);
intent.putExtra("alarm", alarm);
PendingIntent sender = PendingIntent.getBroadcast(ctxt, alarm.id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(), sender);

我的广播接收器:

@Override
public void onReceive(Context context, Intent intent) {
try {

Bundle bundle = intent.getExtras();
final Alarm alarm = (Alarm) bundle.getSerializable("alarm");

Intent newIntent;
if (alarm.type.equals("regular")) {
newIntent = new Intent(context, RegularAlarmActivity.class);
} else if (alarm.type.equals("password")) {
newIntent = new Intent(context, PasswordAlarmActivity.class);
} else if (alarm.type.equals("movement")) {
newIntent = new Intent(context, MovementAlarmActivity.class);
} else {
throw new Exception("Unknown alarm type");
}
newIntent.putExtra("alarm", alarm);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);

} catch (Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
Log.e("AlarmReceiver", Log.getStackTraceString(e));
}
}

此代码不会唤醒设备。但是,当我再次将其转回时,它们会显示出来。我需要让他们打开屏幕。你能帮我解决这个问题吗?

最佳答案

我遇到了类似的问题,解决方案是使用 WakeLocker。应该这样做(最好作为接收器中的第一件事),否则设备会在收到警报时唤醒,但会在 context.startActivity(newIntent) 之前再次休眠;叫做。(我也观察到没有发生这种情况的行为,所以这似乎有点武断)所以简单快速的答案:使用以下源代码创建一个名为 WakeLocker 的新类:

package mypackage.test;

import android.content.Context;
import android.os.PowerManager;

public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;

public static void acquire(Context ctx) {
if (wakeLock != null) wakeLock.release();

PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, MainActivity.APP_TAG);
wakeLock.acquire();
}

public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}

并在您的接收器中调用 WakeLocker.acquire(context); 作为第一件事。额外:一旦你的闹钟完成了它,调用 WakeLocker.release(); 也很整洁。

关于android AlarmManager 没有唤醒手机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6864712/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com