对于某些
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?
>重新启动手机后,“计划”通知或警报消失.但是现在我已经看到这是正常行为,对吗?我怎么能绕过这个呢?