gpt4 book ai didi

android - 使用 AlarmManager 时后台 Activity 被阻止。 (Android Q 隐私更改)

转载 作者:行者123 更新时间:2023-11-29 00:53:25 25 4
gpt4 key购买 nike

在我的项目中,我使用 AlarmManager为了每天触发AlarmClock但是当出现 toast 消息后启动警报的时间到了:

Background activity start from com.example.nameOfApp blocked. See g.co/dev/bgblock

更新代码:

--------setAlarmClock方法--------

private void setAlarmClock(Calendar calendar, int alarmId, String time, String timeOfTheDay, boolean action) {
AlarmManager manager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), AlarmClockReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), alarmId, intent, 0);

if (action) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
} else {
manager.cancel(pendingIntent);
}
}

--------AlarmClockReceiver类--------

public class AlarmClockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String alarmAction = AlarmClock.ACTION_SET_ALARM;
Intent i = new Intent(alarmAction);
i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
i.putExtra(AlarmClock.EXTRA_MESSAGE, "Time for taking medicine!");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}

此外,我在 AndroidManifest 中包含了以下行:

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

我知道它与新的 Android Q 隐私更改有关。来自前述link据说:

Apps running on Android Q can start activities only when one or more of the following conditions are met:

...

The app receives a notification PendingIntent from the system. In the case of pending intents for services and broadcast receivers, the app can start activities for a few seconds after the pending intent is sent.

如果我理解正确的话,这正是我的情况。尽管如此,还是会出现上述 toast 消息。

最佳答案

只有当您使用 setContentIntent 方法在通知中设置 Intent 时,PendingIntent 才有效(为了启动 Activity )。所以你可以做的是发布一个通知而不是直接开始一个 Activity 。当用户点击通知时,挂起的 Intent 将用于启动 Activity 。编辑:作为替代方案,您需要询问 SYSTEM_ALERT_WINDOW权限,但您将无法在 Android Go 上执行该应用,因为无法在该版本上使用此权限。

关于android - 使用 AlarmManager 时后台 Activity 被阻止。 (Android Q 隐私更改),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57330982/

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