大家好,我已经实现了通知功能。 我对通知 ID 有疑问。
这是我的代码:
protected void ShowNotification(String title, String text){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.drawable.atterrato)
.setContentTitle(title)
.setContentText(text)
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(text));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
mBuilder.build();
}
我不想替换通知。
我想增加 0,但我不知道如何解决这个问题。 如果我声明一个变量并销毁该 Activity ,则该 Activity 将不起作用... 有解决这个问题的简单方法吗?
使用 getSharedPreference?
谢谢
最佳答案
如果您计划连续递增一个数字,最好的办法是使用 SharedPreferences
.
首先你需要对其进行初始化:
private void sharedPrefsInit()
{
SharedPreferences sharedPrefs = getSharedPreferences("Number", 0);
// This if statement checks if the number has been accessed before
if(sharedPrefs.getInt("MyNum", -1) == -1)
{
// If it hasn't, create it
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt("MyNum", 0);
editor.commit();
}
}
如果将上述方法放入 onCreate()
中,它将保证您访问的是正确的内容。现在您需要创建一个小方法来为您增加数字,一切就绪。它可能看起来像这样。
private int incMyNum()
{
int newNum;
SharedPreferences sharedPrefs = getSharedPreferences("Number", 0);
newNum = sharedPrefs.getInt("MyNum", -1);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt("MyNum", ++newNum);
editor.commit();
return newNum;
}
现在你的 showNotification()
方法可以有这个
notificationManager.notify(incMyNum(), mBuilder.build());
关于android - 通知 ID 不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24141073/