2016-03-30 18 views
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(); 
} 

}

在此先感谢。

+0

什么数据你fecthing?来自web服务? – Jois

+0

是的,它是由NodeJS返回的JSONArray结果。 – Jarvis

+0

使用凌空图书馆它非常poweful。并且它不消耗太多的电池 – Jois

回答

0

IntentService是一个服务的基类,用于按需处理异步请求(表示为Intents)。客户通过startService(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 
} 

THANKYOU。我希望这可以帮到你。