【发布时间】:2016-07-17 23:24:05
【问题描述】:
我想以固定的时间间隔(比如 30 分钟)从后台获取一些数据。我已经使用警报管理器实现了该解决方案,在该管理器中我以固定的时间间隔调用服务。该过程运行良好,但我面临的问题是它消耗的电池电量很少。我想利用电池消耗,这样用户就不会离开应用程序。警报的设置就像代码的第一部分一样。
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, PollingClass.class);
PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
am.cancel(pi);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60 * 1000, 30 * 60 * 1000, pi);
第二部分中Service类被报警器调用来执行任务。
public class PollingClass extends Service {
private WakeLock mWakeLock;
public PollingClass() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void handleIntent(Intent intent) {
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NEW");
if ((mWakeLock != null) && (mWakeLock.isHeld() == false)) {
mWakeLock.acquire();
}
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (!cm.getBackgroundDataSetting()) {
stopSelf();
return;
}
//Calling an Async class to fetch the data from the server
stopSelf();
}
@Override
public void onStart(Intent intent, int startId) {
handleIntent(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleIntent(intent);
return START_NOT_STICKY;
}
public void onDestroy() {
super.onDestroy();
mWakeLock.release();
}
}
提前致谢。
【问题讨论】:
-
你在输入什么数据??来自网络服务?
-
是的,它是 NodeJS 返回的 JSONArray 结果。
-
使用 volley 库非常强大。而且它不会消耗太多电池
-
仅将 volley 用于请求和响应。我认为问题在于服务或警报管理器,我无法确定可以采取哪些措施来优化它。
-
不要使用服务使用 IntentSERvice
标签: android performance service scheduled-tasks alarmmanager