【问题标题】:Scheduling Background Service to fetch data in Android调度后台服务以在 Android 中获取数据
【发布时间】: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


【解决方案1】:

IntentService 是按需处理异步请求(表示为 Intent)的服务的基类。客户端通过startService(Intent)调用发送请求;该服务根据需要启动,依次使用工作线程处理每个 Intent,并在工作结束时自行停止。 IntentService 有一个后台线程,但仅用于调用 onHandleIntent()。一旦 onHandleIntent() 返回,不仅线程会消失,而且服务也会被破坏。因此,当您在 onHandleIntent() 中实现代码时,这将有助于您的代码在不同的线程中运行。

例如:

@Override
protected void onHandleIntent(Intent intent) {

         //This is where you will put your volley code or some code that you want to perform in background
}

谢谢。我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多