Reputation: 135
Hi guys I have implemented notification feature. I have a problem with notify ID.
This is my code:
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();
}
I do not want to replace a notification.
I want increment the 0, but I don't know how solve this. If I declare a variable and I destroy the activity doesn't work... Is there a simple method for solve this?
Using getSharedPreference?
Thank you
Upvotes: 1
Views: 176
Reputation: 3229
If you plan on continuously incrementing a number, your best bet would be to use SharedPreferences
.
First you need want to have an initialization for it:
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();
}
}
If you put the above method in your onCreate()
, it will guarantee that you're accessing the right thing. Now you'll want to create a small method that increments your number for you and you're all set. It'll probably look like this.
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;
}
Now your showNotification()
method can have this
notificationManager.notify(incMyNum(), mBuilder.build());
Upvotes: 1