gpt4 book ai didi

android - AlarmManager 仅在 App 重启后有效

转载 作者:行者123 更新时间:2023-11-29 01:31:27 59 4
gpt4 key购买 nike

我制作了一个 AlarmManager,它在特定时间启动服务,之后每 30 分钟启动一次服务。该服务启动通知。问题是,我只有在重新启动应用程序后才会收到通知。通知有效,但 AlarmManger 无效,因为我每次重新启动应用程序后都会收到通知。当我重新启动应用程序时并不重要,我每次都会收到通知。

这是我的 AlarmManger 代码:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


Intent myIntent = new Intent(MainActivity.this , MyAlarmService.class);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 4);

alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);
}

这是我的通知代码:

public class MyAlarmService extends Service {

@Override

public void onCreate() {

Intent intent1 = new Intent(this, MainActivity.class);
intent1.putExtra("EXTRA_EVENT_ID", 101);
PendingIntent pI = PendingIntent.getActivity(this, 0, intent1, 0);
Notification noti =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(gr)
.setContentText(r)
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(bigStyle)
.extend(wearableExtender)
.build();

NotificationManagerCompat nM = NotificationManagerCompat.from(this);
nM.notify(0,noti);
}

最佳答案

像这样尝试将 alarmManager 设置为 setRepeating()

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_HALF_HOUR, pendingIntent);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
(30*60*1000), pendingIntent);

关于android - AlarmManager 仅在 App 重启后有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957955/

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