我创建了多个带有不同文本的通知。但是,AlarmManager始终显示具有相同文本的通知,如果以前的通知没有被滑动删除,则替换旧通知。NOTIFY_ID始终不同(已调试)。此外,我发现如果在显示通知后在onRecieve方法中崩溃应用程序,它可以正常工作... 以下是代码:
public class Schedule extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wakeLock.acquire();
//next is notification code. //
//get res.
SharedPreferences mPrefs = context.getSharedPreferences("appsettings", 0);
String titleText = mPrefs.getString("titleText", "");
String bigText = mPrefs.getString("bigText", "");
int NOTIFY_ID = mPrefs.getInt("id", 0);
//create intent.
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//get res.
Resources res = context.getResources();
//build notification.
Notification.Builder builder = new Notification.Builder(context)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.statusbaricon)
.setAutoCancel(true)
.setContentTitle(titleText)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(bigText);
//check vibration.
if (mPrefs.getBoolean("vibration", true)) {
builder.setVibrate(new long[] { 0, 50 });
}
//create default title if empty.
if (titleText.length() == 0) {
builder.setContentTitle(context.getString(R.string.notification_Title_Default));
}
//show notification. check for delay.
builder.setWhen(System.currentTimeMillis());
Notification notification = new Notification.BigTextStyle(builder)
.bigText(bigText).build();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFY_ID, notification);
////
wakeLock.release();
}
public void setAlarm(Context context) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
int delay = mPrefs.getInt("delay", 0);
int id = mPrefs.getInt("id", 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, Schedule.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_ONE_SHOT);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() /* + 1000 * 60 * delay */, pendingIntent);
}
}
这就是我所谓的:
//store stuff to revoke in Schedule.
mPrefsEditor.putString("bigText", bigText).apply();
mPrefsEditor.putString("titleText", titleText).apply();
Schedule schedule = new Schedule();
schedule.setAlarm(context);