Reputation: 71
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);
}
}
Upvotes: 0
Views: 2201
Reputation: 8638
You should use AlarmManager
to schedule your task in service.
Take these steps:
Define and implement your method to update DB in a Service class.
Define BroadcastReceiver
that is responsible for calling Service class to do the task.
AlarmManager
to schedule the task.This link does exactly (not exactly) what you want to do. Don't know much about SyncAdapter so won't comment on it.
Upvotes: 2
Reputation: 1008
well from my side one more way is that call that service while change device date.
while user will open application at that time check data and if date is changed then previous date then call service.
your 24 hr service will run in background and may take load also if it continuously check time and wait for 24 hr.
Upvotes: 0