例如,用户设置他想要通知的日期(接收电影结束的推送通知)。为此,我将电影的 id 设置为BroadcastReceiver,我还会拍摄电影的 名称 ;使用它作为广播接收器的文本消息,例如,“movieName out out”,方法是SetAlarm()。注意:我的应用程序不需要对电影做任何事情,我说的一般。
public void setAlarm(View view){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
Intent alertIntent = new Intent(this, AlertReceiver.class);
alertIntent.putExtra("id", mainId);
alertIntent.putExtra("name", name);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
PendingIntent.getBroadcast(this, 1, alertIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
}
正如你所看到的那样,我正在将一部电影的id和名称传递给AlertReceiver类
public class AlertReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int id = intent.getIntExtra("id", 0);
String name = intent.getStringExtra("name");
createNotification(context, "Movie", name + " Now Out" , name, id);
}
public void createNotification(Context context, String msg, String msgText, String msgAlert, int id){
//intent for MainActivity
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setContentTitle(msg)
.setContentText(msgText)
.setTicker(msgAlert)
.setSmallIcon(R.mipmap.ic_launcher);
//the intent when the notification is clicked on
mBuilder.setContentIntent(notificIntent); //goes to MainActivity
//how the user will be notified
mBuilder.setDefaults(NotificationCompat.DEFAULT_LIGHTS);
//stop notification when it's clicked on
mBuilder.setAutoCancel(true);
//now to notify the user with NotificationManager
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, mBuilder.build());
}
}
它运行良好,用户只有在应用程序仍在后台运行时才会收到通知,但在关闭或重新启动后,广播接收器仍会被调用;用户会收到通知,这表示 id 没有问题,但 名称 为空,我得到了短信“null is out”。那我怎么能保存这个名字呢?
答案 0 :(得分:-1)
使用SharedPreference
保存用户名。
答案 1 :(得分:-1)
<强> SharedPreference 下,的磁盘强>,<强>数据库强> ...
推荐 SharedPreference