2013-07-31 32 views
1

在我的活動中,我有一個私人BroadcastReceiver,當觸發時,應該更新一些毫秒後的用戶界面。在我的活動,我有:BroadcastReceiver和PostDelay

private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
    Log.e("BroadCastReciever: ", "UpdateCaseList"); 
    update.RefreshCaseList(); 
    } 
}; 

BroadcastReceiver是beeing從Service觸發:

@Override 
    public void onCreate() { 
     super.onCreate(); 
     intent = new Intent(BROADCAST_ACTION); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     handler.removeCallbacks(sendUpdatesToUI); 
     handler.postDelayed(sendUpdatesToUI, 0); 
    } 

    private Runnable sendUpdatesToUI = new Runnable() { 
     public void run() { 
      handler.postDelayed(this, 10000); // 10 seconds 
      sendUpdateToUiThread();   
     } 
    }; 

    private void sendUpdateToUiThread() { 
     sendBroadcast(intent); 
    } 

我想,當我在OnResume()方法註冊的BroadcastReceiver的onStart方法被調用。我還註銷中的BroadcastReceiver

我的意圖是,這應該每10秒向Activity發送一個通知。一旦我啓動應用程序,我的服務將按計劃每隔10秒通知活動。問題是,當我離開活動並返回時,它不會每隔10秒向activity發出通知,但只是在隨機時間。我可以在LogCat中看到,這種隨機性垃圾郵件每4,6,3,8,6秒發生一次等等。爲什麼地球上這種行爲?

+1

是否有使用從API級別5棄用的'onStart'回調的原因?確保只有在'Service'沒有運行時才調用'startService()'。 – Luksprog

+0

如果onStart方法已棄用,您能否建議其他解決方案?謝謝。 –

+1

您有http://developer.android.com/reference/android/app/Service.html#onStartCommand%28android.content.Intent,%20int,%20int%29方法。 – Luksprog

回答

0

根據postDelayed documentation 了Runnable叫 millisecods經過和

時間在深睡眠中度過將額外的延遲添加到執行。

所以一些隨機性是有意設計的。所以我期望Runnable在之後調用更多在您的情況下超過10000 ms。