Reputation: 1862
I've a service that runs after the Android devices boots up. This executes two notifications every day. But I've a problem: It looks like the the service crashes or automatically restarts. Also the notifications are not executed at the specified time. How can I fix this? Sometime I see the toast Service Created
and Service Started
. Thanks!
The code:
public class UnUsedService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private PendingIntent pendingIntent;
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, 05); //midday
cal1.set(Calendar.MINUTE, 45);
cal1.set(Calendar.SECOND, 00);
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, 17);//8pm for example
cal2.set(Calendar.MINUTE, 30);
cal2.set(Calendar.SECOND, 00);
AlarmManager am = (AlarmManager)getApplicationContext().getSystemService (Context.ALARM_SERVICE);
Intent intent2 = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(),cal2.getTimeInMillis(), pi);
}
};
Upvotes: 0
Views: 726
Reputation: 39807
If your notices need to run at a particular time, you should be using AlarmManager to schedule them. This gets retained by Android, so that your service is free to be killed and the alarm will restart it when necessary.
It sounds like you're currently letting your service run 24/7 just so that it can do something twice a day; this is being a bad Android citizen! Using the AlarmManager
instead will fix your problem and also let you stop wasting resources.
Upvotes: 1