android - 通知 ID 不变

标签 android

大家好,我已经实现了通知功能。 我对通知 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/

相关文章:

android - In App Billing 是否支持多个帐户?

android - layout_weight 不适用于 Drawerlayout 内的 LinearLayout

android - 有没有Android Beam失败回调

java - Android 保存字符串

Android 应用程序内存不足错误,尝试使用 88kb 图像

android - Mapquest,apiKey重要吗?

java - 如何在android中读取xml文件?

Android:EditText TextChangedListener 上的堆栈溢出错误

java - 提醒推送通知不执行弹出功能

android - 如何在 ActionBar 的图标和向上按钮之间添加填充/边距?