如何定期查询db并定期删除行的定期任务?

时间:2016-11-07 23:15:25

标签: android android-contentprovider

如何实现定期查询db并定期删除行的任务?我想这样做,以防止我的数据库随着时间的推移而变得太大。

1 个答案:

答案 0 :(得分:0)

使用粘性ServiceAlarmManagerBroadcastReceiver是您需要的。

public class MY_SERVICE extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

     // remove last alarm you set
     Intent intent = new Intent(context, MY_DB_PROCEDURE_BROADCAST.class);
    intent.setAction("myDbProcedure");
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context,1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.cancel(alarmIntent);

    // add new alarm manager
    intent = new Intent(context, MY_DB_PROCEDURE_BROADCAST.class);
    intent.setAction("myDbProcedure");
    alarmIntent = PendingIntent.getBroadcast(ct, 1, intent, 0);
    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(),
            intervalMin*60*1000, alarmIntent);

    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

你的BroadcastReceiver课程:

public class MY_DB_PROCEDURE_BROADCAST extends BroadcastReceiver {

    private final String TAG=getClass().getName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG,"Started");
        // DO YOUR DB TASK HERE
    }

}

在你的清单中定义服务和broadcastReceiver:

<service
        android:name="MY_SERVICE"
        android:enabled="true"
        android:exported="true" />

 <receiver android:name="MY_DB_PROCEDURE_BROADCAST" android:enabled="true"/>