我正在開發一個原生的android應用程序,每30分鐘運行一次備份操作。與AlarmManager和WakeLocks相關的問題
我使用AlarmManager
爲此目的,它工作正常。下面是我使用啓動報警代碼:
public static void startSync(Context context) {
alarmIntent = new Intent(context, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// int interval = 3600000;
int interval =30000 ;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(context, "Sync Started", Toast.LENGTH_SHORT).show();
}
這裏是上接收方法:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
PowerManager pm = (PowerManager) context.getSystemService(context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
Intent eventService = new Intent(context, SyncInBackground.class);
context.startService(eventService);
wl.release();
}
}
我注意到,當我的設備不處於待機狀態,操作了5秒(我以編程方式計算),但是當手機處於待機模式時,花了11秒。這就是爲什麼我在後臺服務中運行備份操作之前使用wake_lock
的原因,以便使應用程序僅需5秒。
但是,如果手機處於待機模式,仍然會得到相同的結果...如果不處於待機模式,它仍然需要11秒和5秒。
我能做些什麼來使我的後臺服務在5秒內運行重複鬧鐘而不是11秒?