【发布时间】:2016-12-30 11:28:55
【问题描述】:
嗨,我需要每 4 秒调用一次方法,即使设备处于睡眠状态,我也使用带有服务 Start_stick 的警报管理器,服务名称是 TransactionService。当设备处于活动状态并且每隔 4 秒调用一次该方法时,该代码运行良好,但是当屏幕被锁定并且设备休眠时,调用变得不准确。所以该方法现在每 2 秒调用一次,有时每 1 秒调用一次,5 ....
这就是我运行线程以每 4 秒调用一次方法的方式
AlarmManager mgr = (AlarmManager) getApplicationContext().getSystemService(
Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(getApplicationContext(),
TransactionService.class);
PendingIntent pendingIntent = PendingIntent.getService(
getApplicationContext(), 0, notificationIntent, 0);
mgr.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 4000, pendingIntent);
这是设备处于活动状态且屏幕打开时调用方法的日志
12-30 13:23:00.565 17397-17479/com.ids.simcardrefill D/url: calling
12-30 13:23:04.565 17397-17537/com.ids.simcardrefill D/url:calling
12-30 13:23:08.565 17397-17411/com.ids.simcardrefill D/url:calling
12-30 13:23:12.565 17397-17655/com.ids.simcardrefill D/url:calling
这就是设备休眠时方法的调用方式
12-30 13:09:12.565 17397-17655/com.ids.simcardrefill D/url:calling
12-30 13:09:17.785 17397-17598/com.ids.simcardrefill D/url:calling
12-30 13:09:20.565 17397-17479/com.ids.simcardrefill D/url:calling
12-30 13:09:25.775 17397-17537/com.ids.simcardrefill D/url:calling
12-30 13:09:28.565 17397-17411/com.ids.simcardrefill D/url:calling
这里调用的区别是不准确的:2秒、5秒、3秒
这就是服务的样子:
public int onStartCommand(Intent intent, int flags, int startId) {
mshared = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
edit = mshared.edit();
hostname = mshared.getString(
getApplicationContext().getString(R.string.hostname), "0");
contin = true;
cost
= mshared.getString(getString(R.string.test), "0.09");
if (contin) {
getTransactions get = new getTransactions(getApplicationContext());
get.execute(hostname);
}
return START_STICKY;
}
`
任何解决方案??
【问题讨论】:
-
使用唤醒日志来实现。
-
嗨 Malo,您可以在前台使用服务并调用您的 AlarmManger 任务,就像 startForgroundService(true),truiton.com/2014/10/android-foreground-service-example
-
时间变得“不准确”是由于 Android (6.0+) 将网络活动捆绑到更大的批次以节省电池时间。无论如何,如果您需要每 4 秒执行一次在线调用,则 API 的设计可能有问题。每 4 秒轮询一次是一种糟糕的风格,就像忙着等待一样。
-
设备只能在这个应用中工作,并且一直连接充电,而且操作系统是4.4.1而不是6.0+。
-
请不要这样做。应用程序会消耗电池,没有人会喜欢它。无论您想做什么,都有另一种方法。
标签: java android multithreading