2014-02-10 28 views
1

我目前正試圖顯示從IntentService,如果設備檢測到加速度計吐司。爲此,我搜索並瞭解到我可以實施處理程序。但是,它不是很有效。該代碼編譯並在模擬器上運行時沒有任何錯誤,但吐司不顯示。我想知道是否可以幫助我發現代碼中的錯誤。代碼如下所示。Totent從IntentService發佈與處理程序不會顯示何時在onHandleIntent中創建處理程序

任何幫助,將不勝感激!

public class AccelService extends IntentService implements SensorEventListener{ 
    private SensorManager mySensorManager; 
    private Handler toastHandler; 

    public AccelService(){ 
     super("AccelerometerIntentService"); 
    } 
    ... 
    private class ToastRunnable implements Runnable{ 
     String toastText; 
     public ToastRunnable(String text){ 
      toastText = text; 
     } 
     @Override 
     public void run(){ 
      Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show(); 
     } 
    } 
    @Override 
    protected void onHandleIntent(Intent intent){ 
     toastHandler = new Handler(); 
     initialize(); 
    } 
    public void initialize(){ 
     mySensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
     if(mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){ 
      toastHandler.post(new ToastRunnable("Accelerometer Detected!")); 
     } 
    } 
    ... 
} 
+0

http://stackoverflow.com/questions/5346980/intentservice-wont-show-toast?rq=1 – marcinj

+0

記錄如果runnable被執行並嘗試getBaseContext()作爲上下文參數 – Sam

+0

@ marcin_j:我不太確定解決建議的帖子是正確的。 IntentService引用提到'onStartCommand'方法不會被覆蓋。此外,Handler的全部意義在於IntentService在不同的線程中運行並作爲解決方案。 – ElectroJunkie

回答

1

創建於onHandleIntent敬酒的消息處理程序綁定到錯誤的線程:

該方法被調用工作線程與處理請求。

顯式設置處理程序的線程,例如使用new Handler(getMainLooper())或在onCreate中創建處理程序。

相關問題