我正在开发一个原生的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秒?