2013-03-12 83 views
0

我想在60秒後定期調用特定的代碼以獲取應用程序中的更新數據。我想知道我應該把代碼放在主Android活動中。任何幫助將不勝感激 感謝Android獲取時間更新

+0

創建一個線程,並調用的AsyncTask在每一分鐘 – Pragnani 2013-03-12 07:03:35

+0

謝謝,你可以分享的線程代碼樣本和我應該在哪裏放置的代碼在android活動? – CodeAddiction 2013-03-12 07:05:11

+1

檢查此鏈接http://android-developers.blogspot.kr/2007/11/stitch-in-time.html – Pragnani 2013-03-12 07:14:17

回答

1

您可以使用Timer類Java的util包。它將允許您再次定期執行特定代碼&。看看每5秒執行一次的example

0
import android.os.Handler; 

public class ExecuteEveryMinuteExample { 
    private static final int DELAY_IN_MILLIS = 60000; 

    private final Handler handler; 
    private final Runnable task; 

    public ExecuteEveryMinuteExample(Handler handler, Runnable runnable) { 
     this.handler = handler; 
     this.task = new Task(runnable); 
    } 

    public void start() { 
     handler.postDelayed(task, DELAY_IN_MILLIS); 
    } 

    public void stop() { 
     handler.removeCallbacks(task); 
    } 

    private class Task implements Runnable { 
     private Runnable task; 

     private Task(Runnable runnable) { 
      this.task = runnable; 
     } 

     @Override 
     public void run() { 
      task.run(); 
      start(); 
     } 
    } 
} 

這種「定時」與活動相關的生命週期,記得在Activity#onPause停止它在Activity#onDestroy或更好。還可以結賬Timer,ScheduledThreadPoolExecutorTimerTask它們可能更適合您的需求。

0

在android中使用服務和廣播接收器。

// Restart service every 30 seconds 
    private static final long REPEAT_TIME = 1000 * 30; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
    AlarmManager service = (AlarmManager) context 
     .getSystemService(Context.ALARM_SERVICE); 
    Intent i = new Intent(context, MyStartServiceReceiver.class); 
    PendingIntent pending = PendingIntent.getBroadcast(context, 0, i, 
     PendingIntent.FLAG_CANCEL_CURRENT); 
    Calendar cal = Calendar.getInstance(); 
    // Start 30 seconds after boot completed 
    cal.add(Calendar.SECOND, 30); 
    // 
    // Fetch every 30 seconds 
    // InexactRepeating allows Android to optimize the energy consumption 
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP, 
     cal.getTimeInMillis(), REPEAT_TIME, pending); 

請參閱本網站以獲取更多信息。

http://www.vogella.com/articles/AndroidServices/article.html

+0

在我看來,使用服務更新時間視圖是矯枉過正。 – delor 2013-03-12 08:28:24