Notifications That Open By Themselves
the notifications of my app open without a logical sense than the code that I wrote. I should receive a notification every day at the same time but if I open the app I get the same
Solution 1:
The service runs when you register it, so what you need to do is pass a boolean value with the intent when registering the service to prevent it from running when the application runs, but to run periodically thereafter.
In your activity add:
intent.putExtra("run", false);
Then in MyAlarmService:
privatebooleanrun=true;
// ...
action.getBooleanExtra("run", run);
if(run) {
// notifications code
} else {
run = true;
}
Solution 2:
Actually it works exactly as code is written. The cause of that behavior is your startAt
parameter in setRepeating
method.
am.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
24*60*60*1000,
pendingIntent);
calendar.getTimeInMillis()
time in milliseconds that the alarm should first go off, using the appropriate clock (depending on the alarm type).
For example :
//send first alarm after 1 second and repeat it every 24 hours
am.setRepeating(AlarmManager.RTC_WAKEUP,
1000,
24*60*60*1000,
pendingIntent);
//send first alarm after 10 second and repeat it every 24 hours
am.setRepeating(AlarmManager.RTC_WAKEUP,
10000,
24*60*60*1000,
pendingIntent);
UPDATE :
You need to save your last update time :
publicclassMyAlarmServiceextendsBroadcastReceiver {
NotificationManager nm;
@OverridepublicvoidonReceive(Context context, Intent intent) {
//send alarm here//...SharedPreferencesmPref= context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
SharedPreferences.EditormEditor= mPref.edit();
mEditor.putLong("UPDATE_TIME", time);
mEditor.commit();
}
}
Then you can make your setRepeatingAlarm
method like this :
publicvoidsetRepeatingAlarm() {
Intentintent=newIntent(this, MyAlarmService.class);
PendingIntentpendingIntent= PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
long startAt;
long period;
SharedPreferencesmPref= context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
longdif= System.currentTimeMillis() - mPref.getLong("UPDATE_TIME", 0);
if (dif >= UPDATE_PERIOD) {
startAt = 0;
period = UPDATE_PERIOD;
} else {
startAt = dif;
period = dif;
}
am.setRepeating(
AlarmManager.RTC_WAKEUP,
startAt,
period,
pendingIntent);
}
Post a Comment for "Notifications That Open By Themselves"