1
我想在固定的时间间隔(例如30分钟)从后台获取一些数据。我已经实施了使用报警管理器的解决方案,我在固定时间间隔内调用服务。这个过程工作正常,但我面临的问题是它的电池电量很少。我想利用电池消耗,以便用户不会逃离应用程序。警报像代码的第一部分一样设置。调度后台服务以获取Android中的数据
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);
在第二部分中,服务类被警报调用来执行任务。
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();
}
}
在此先感谢。
什么数据你fecthing?来自web服务? – Jois
是的,它是由NodeJS返回的JSONArray结果。 – Jarvis
使用凌空图书馆它非常poweful。并且它不消耗太多的电池 – Jois