Reputation: 1
I need to delete a row in sqlite
database on specific time, exactly in midnight.
I do like the following code :
Calendar currentCalendar = Calendar.getInstance();
Date currentTime = currentCalendar.getTime();
Calendar setCalendar = Calendar.getInstance();
setCalendar.set(Calendar.HOUR_OF_DAY, 0);
setCalendar.set(Calendar.MINUTE,0);
setCalendar.set(Calendar.SECOND,0);
Date setTime = setCalendar.getTime();
if(currentTime.after(setTime)){
// do another task
}else{
databaseHandler.deleteRow(String.valueOf(listSession.get(0).getId()));
}
With code above, the row is deleted but i have to open the application first.
My question is : Is there any possibility how to delete row is sqlite without open the apps? If any, how?
Upvotes: 0
Views: 279
Reputation: 341
Create a android service and BroadcastReceiver and put your above code in onreceive function of BroadcastReceiver and call this BroadcastReceiver in onstart function of service.
Upvotes: 0
Reputation: 266
You can use AlarmManager. First create a BroadcastReceiver.
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Delete your row here.
}
Then set an alarm for it.
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60000, pendingIntent);
Don't forget to add your receiver to your manifest file.
<receiver android:name="AlarmReceiver"/>
Upvotes: 1