在我的應用程序中,我使用一個按鈕來更新我的sqlite數據庫,但現在我想在每24小時後自動更新一次數據庫。我怎樣才能做到這一點?我試過使用CountDownTimer,但是當我的應用程序沒有運行時,這不起作用。我嘗試了待處理的意圖和報警管理器,但它不能正常工作(P.S:我測試了10秒而不是24小時)。當我開始我的活動,然後停止並且不起作用時,它第一次工作。這是我試過的代碼:如何在Android中每24小時更新一次數據庫
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);
}
}
服務類:
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);
}
}
添加後臺服務類並在24小時更新後調用。 – Destro
使用同步適配器 –
你試圖設置24小時阿拉姆嗎?如果它工作,你可以使用相同的代碼同步數據庫 – Sree