android 实现定时通知,在Android中创建定时通知(例如,针对事件)
對于某些Android應用程序,我想集成以下功能:
用戶可以定義他想要被提醒的時間.當時間到了,應用程序應該在通知欄中創建通知,即使此時用戶沒有使用該應用程序.
為此,需要查看AlarmManager,NotificationManager和Notification.Builder類,對吧?
那么我該如何提前創建定時通知呢?我的代碼(到目前為止)是這樣的:
將其添加到AndroidManifest下以注冊廣播接收器:
創建一個新的類文件來處理它收到的警報:
public class AlarmNotificationReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String additionalData = extras.getString("displayText");
// show the notification now
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification mNotification = new Notification(R.drawable.ic_launcher, context.getString(R.string.app_name), System.currentTimeMillis());
PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); // open MainActivity if the user selects this notification
mNotification.setLatestEventInfo(context, context.getString(R.string.app_name), additionalData, pi);
mNotification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_SOUND;
mNotificationManager.notify(1, mNotification);
}
}
}
使用此代碼(例如在MainActivity中)將警報設置為3秒后:
Intent i = new Intent(this, AlarmNotificationReceiver.class);
i.putExtra("displayText", "sample text");
PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), 234324246, i, 0);
AlarmManager mAlarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+3*1000, pi);
為了使這項工作,我需要改變什么?謝謝!
這兩個問題是:
>當我在代碼中更改通知時,通知的文本不會更改.它只會在我更改PendingIntent.getBroadcast(…)中的requestCode時更改.這個請求代碼到底是什么?可以是隨機值還是0?
>重新啟動手機后,“計劃”通知或警報消失.但是現在我已經看到這是正常行為,對嗎?我怎么能繞過這個呢?
解決方法:
對第1部分不確定,但對于第2部分,一般方法是攔截BOOT_COMPLETED意圖并使用它重新注冊所有警報.遺憾的是,對于您在警報管理器中注冊的每個警報,您都必須將其存儲在應用程序的數據庫中.
因此,您需要一個廣播接收器來攔截BOOT_COMPLETED意圖:
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// get your stored alarms from your database
// reregister them with the alarm manager
}
}
要獲取BOOT_COMPLETED意圖,您必須在清單中添加以下權限:
并且BootReceiver還需要使用以下intent過濾器在您的清單中注冊:
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
重要的是要注意,如果您的應用程序安裝到SD卡,它永遠不會收到BOOT_COMPLETED意圖.此外,值得注意的是,這種實現有點天真,因為它在啟動時立即執行代碼,這會在啟動時降低用戶的手機速度.因此,我建議在攔截啟動意圖后將執行延遲幾分鐘.
標簽:android,notifications,alarmmanager
來源: https://codeday.me/bug/20190521/1146859.html
總結
以上是生活随笔為你收集整理的android 实现定时通知,在Android中创建定时通知(例如,针对事件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 多行 对齐方式,andr
- 下一篇: 相互宝赔付30万到账多少