2016-11-04 83 views
1

重複HTTP請求最簡單的方法是什麼(即每45分鐘)? 我不想使用任何推送通知 我已經試過AlarmManager,但它沒有工作。Android:重複HTTP請求

Forground Service可能是一種好方法,但它可能會消耗太多電量。

+0

使用阿拉姆馬槽,它使用更少的電池和完美的工作。如果我想給你完整的源代碼。 –

+0

請,如果可以的話,給我一個例子,爲它! –

回答

0

調用此梅託德從您的MainActivity:

private void setNotifyAlarm() { 
     long _alarm; 
     Calendar now = Calendar.getInstance(); 
     Calendar wakeupcall = Calendar.getInstance(); 
     wakeupcall.setTimeInMillis(System.currentTimeMillis()); 
     wakeupcall.set(Calendar.HOUR_OF_DAY, 15); 
     wakeupcall.set(Calendar.MINUTE, 30); 

     if (wakeupcall.getTimeInMillis() <= now.getTimeInMillis()) 
      _alarm=wakeupcall.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1); 
     else 
      _alarm=wakeupcall.getTimeInMillis(); 


     al = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 
     notif= new Intent(this,NotifyService.class); 
     fintent = PendingIntent.getService(this,0,notif,0); 
     al.setRepeating(AlarmManager.RTC_WAKEUP,_alarm,"45 minutes in Miliseconds", fintent); 

創建服務的HTTP requuest:NotifyService.java

public class NotifyService extends Service { 


    private NotificationManager mNotificationManager; 
    PowerManager powerManager; 
    PowerManager.WakeLock wakeLock; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     powerManager = (PowerManager) getSystemService(POWER_SERVICE); 
     wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NOTIFY"); 

    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    private void handleSERVICE(Intent intent){ 
     new NotifyTASK().execute(); 
    } 

    private class NotifyTASK extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected Void doInBackground(Void... voids) { 
      { 
      DO your HTTP CALLS 

      } 
      stopSelf(); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void aVoid) { 
      super.onPostExecute(aVoid); 
     } 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     wakeLock.acquire(); 
     handleSERVICE(intent); 
     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     wakeLock.release(); 
    } 
} 

現在加入這個清單文件:

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> 
<uses-permission android:name="android.permission.WAKE_LOCK"/> 

<service android:name=".NotifyService" android:exported="true" android:enabled="true"/> 

此代碼以指定的時間間隔開始服務。 希望這對你有所幫助,如果你需要更多的代碼然後告訴我。