2015-06-24 48 views
0

我想在5分鐘的時間間隔後在後臺運行一些任務(從數據庫中提取數據)。我應該使用什麼?定期在後臺運行任務

+0

使用線程的實現它 –

+0

使用服務來達到同樣的 –

+1

AlarmManager用的PendingIntent可以工作太 – chiragjn

回答

0

可以使用TimerTask裏面有服務

Timer timer = new Timer(); 
timer.schedule(new YourTask(), 50000); 
0

試試這個。

Timer timer = new Timer(); 
    timer.scheduleAtFixedRate(new TimerTask() { 

    @Override 
    public void run() { 
    //Do something 

    } 
    }, 0, 5000); 
0

使用異步任務:

前執行,做inBackground,後執行

帶報警經理

Intent myIntent1 = new Intent(sign_in.this,MyNotificationService.class); 
         pendingintent2 = PendingIntent.getService(sign_in.this, 1,myIntent1, 1); 
         AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE); 
         Calendar calendar1Notify = Calendar.getInstance(); 
         calendar1Notify.setTimeInMillis(System.currentTimeMillis()); 
         calendar.add(Calendar.SECOND, 20); 

         alarmManager1.set(AlarmManager.RTC_WAKEUP,calendar1Notify.getTimeInMillis(), pendingintent2); 

         long time = 300*1000;// 5 minutes repeat 

alarmManager1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1Notify.getTimeInMillis(),time,pendingintent2); 

添加權限清單中

<service android:name="com.example.MyNotificationService" > 

     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     </intent-filter> 
    </service> 
0

可以我們e計時器任務:

TimerTask scanTask; 
final Handler handler = new Handler(); 
Timer t = new Timer(); 

public void doTask(){ 

scanTask = new TimerTask() { 
     public void run() { 
       handler.post(new Runnable() { 
         public void run() { 
          //your task(fetch data) 
         } 
       }); 
     }}; 

    t.schedule(scanTask, 300000, 300000); 
} 
0

請注意,Google要求您在服務上運行長時間的操作。請閱讀以下文章,以確定您需要什麼服務(服務,服務)!

意圖服務在作業完成後自行關閉。 要每5分鐘啓動一次服務來完成這項工作,您可以按照上面的建議與計時器結合使用。

請注意繼續:服務屬於同一個線程,您在其中創建它。因此,當您即將開發您的服務時,請使用新的線程來啓動它。如果你忘記這樣做,你的服務將屬於UI線程,意味着你是一個麻煩.... 首先閱讀: http://developer.android.com/guide/components/services.html

開發指南: http://developer.android.com/reference/android/app/Service.html

0

您可以使用計時器,這不是一個問題,但Android的中方法也有一定的優勢

private int mInterval = 5000; // 5 seconds by default, can be changed later 
    private Handler mHandler; 

    @Override 
    protected void onCreate(Bundle bundle) { 
    ... 
    mHandler = new Handler(); 
    } 

    Runnable mStatusChecker = new Runnable() { 
    @Override 
    public void run() { 
     updateStatus(); //this function can change value of mInterval. 
     mHandler.postDelayed(mStatusChecker, mInterval); 
    } 
    }; 

    void startRepeatingTask() { 
    mStatusChecker.run(); 
    } 

    void stopRepeatingTask() { 
    mHandler.removeCallbacks(mStatusChecker); 
    }