對於某些Android應用程序,我想集成以下功能: 用戶可以定義他想要提醒某事的時間。當時間到了,應用程序應該在通知欄中創建通知,即使此時用戶不使用該應用程序。在Android中創建定時通知(例如用於事件)
爲此,需要查看類AlarmManager,NotificationManager和Notification.Builder,對吧?
那麼如何提前創建定時通知?我的代碼(到目前爲止)是這樣的:在
添加這個到AndroidManifest註冊的廣播接收器:
<receiver android:name="AlarmNotificationReceiver"></receiver>
創建一個新的類文件,它處理它接收到報警:
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?
- 重新啓動手機後,「計劃」通知或鬧鐘消失。但現在我已經看到這是正常的行爲,對吧?我怎樣才能繞過這個?
到目前爲止什麼都不工作? – 2012-01-06 01:31:17