In my application I'm using a button to update my sqlite database but now I want to update my database automatically after every 24 hours. How can I do this? I tried using CountDownTimer but that does not work when my app isn't running. I tried pending Intent and Alarm Manager but it isn't working properly(P.S: I tested it for 10 seconds instead of 24 hrs). It works for the 1st time when I start my activity and then it stops and doesn't work. Here's the code I tried:
public class Activity_Settings extends ActionBarActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent notificationIntent = new Intent(mActivity, MyAlarmService.class);
PendingIntent contentIntent = PendingIntent.getService(mActivity, 0,
notificationIntent,0);
AlarmManager am = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
am.cancel(contentIntent);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ AlarmManager.INTERVAL_DAY * 1, AlarmManager.INTERVAL_DAY *
1, contentIntent);
}
}
Service class:
public class MyAlarmService extends Service {
@Override
public void onCreate() {
// TODO Auto-generated method stub
Intent mainIntent = new Intent(this,Activity_Settings.class);
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
// update database
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}