如何解决Android Studio AlarmManager在特定时间未运行
这是警报管理器的代码:
protected void alarmInit(){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,9);
calendar.set(Calendar.MINUTE,25);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this,SampleBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getbroadcast(this.getApplicationContext(),234324243,alarmIntent,0);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
这是broadcast类:
public class SampleBootReceiver extends broadcastReceiver {
@Override
public void onReceive(Context context,Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_LONG).show();
intent = new Intent(context,NotificationService.class);
PendingIntent pIntent = PendingIntent.getActivity(context,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context)
// Set Icon
.setSmallIcon(R.drawable.icono)
// Set Ticker Message
.setTicker("message")
// Set Title
.setContentTitle("asdf")
// Set Text
.setContentText("message")
// Add an Action Button below Notification
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
notificationmanager notificationmanager = (notificationmanager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0,builder.build());
}
}
}
}
但是在设定的时间我没有收到任何消息(我看不到Toast消息,带有单词Hello)。 另外,在清单XML中,我在aplication标签内设置了
<receiver android:name=".Home$SampleBootReceiver"
android:enabled="false"
tools:ignore="Instantiatable">
SampleBootReceiver类是Home类中的公共类
您能帮我吗?预先感谢
解决方法
您正在使用setInexactRepeating
,因此操作系统将决定何时触发警报。操作系统尝试将警报分组以节省电池。
从API 19(Build.VERSION_CODES.KITKAT)开始,警报传递是 不精确:操作系统将转移警报,以最大程度地减少唤醒和 电池使用。有新的API支持需要的应用程序 严格的交货保证;参见setWindow(int,long,long, android.app.PendingIntent)和setExact(int,long, android.app.PendingIntent)。 targetSdkVersion为 API 19之前的版本将继续在中看到以前的行为
https://developer.android.com/reference/android/app/AlarmManager
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。