2012-09-04 50 views
0

我嘗試添加一個對話框到BluetoothChatService中,如果無法建立或丟失連接,將提示重試藍牙連接。當AlertDialog.show()被執行時,我得到一個運行時異常;這個錯誤發生在Handler.java中,錯誤爲「無法在未調用Looper.prepare()的線程中創建處理程序」,並且mLooper爲空。 我嘗試了其他解決方案,發現在stackoverflow,如'新AlertDialog.Builder(Activity.this)';沒有任何工作。AlertDialog.Builder RuntimeException

編輯:似乎線程內的對話方法是問題。我將在創建線程的UI活動的約束內重新編寫對話框。感謝所有的迴應。

代碼:

public class BluetoothChatService { 

private Context context; 
private final BluetoothAdapter mAdapter; 
private int mState; 

public BluetoothChatService(Context context) { 
    this.context = context; 
    mAdapter = BluetoothAdapter.getDefaultAdapter(); 
    mState = STATE_NONE; 
} 

private void connectionFailed(String s) { 
    // Send a failure message back to the Activity 
    stop(); 
    sendToastMessage(String.format(context.getApplicationContext().getString(R.string.bluetooth_cannot_connect), s)); 
    createRetryDialog(R.string.bluetooth_cannot_connect, s); 
} 

// --------------------------------------------------------------------------------------------- 
private void createRetryDialog(int msg_id, String err_msg) { 
    AlertDialog.Builder alertDialogBuilderRetry; 
    alertDialogBuilderRetry = new AlertDialog.Builder(context); 
    String message = String.format(context.getApplicationContext().getString(msg_id), err_msg); 

    // set title 
    alertDialogBuilderRetry.setTitle(context.getApplicationContext().getString(R.string.bluetooth_title_connect_error)); 

    // set dialog message 
    alertDialogBuilderRetry 
     .setMessage(message) 
     .setCancelable(false) 
     .setPositiveButton(context.getApplicationContext().getString(R.string.dialog_button_yes), new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog,int id) { 
       // Start the service over to restart listening mode 
       initializeBluetooth(); 
       dialog.dismiss(); 
      } 
     }) 
     .setNegativeButton(context.getApplicationContext().getString(R.string.dialog_button_no),new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog,int id) { 
       // if this button is clicked, just close 
       // the dialog box and do nothing 
       mState = STATE_NONE; 
       dialog.cancel(); 
      } 
     }).create().show(); 
} 
} 
+2

你不能在服務中創建或顯示對話框..只有主UI線程可以做到這一點.. – user370305

+0

我看到你已經把這個工作放到它自己的類中。你可以在你使用這個類的地方發佈代碼嗎?看起來你可能試圖從服務或後臺線程而不是UI線程來完成它。 – FoamyGuy

回答

0

確保當你調用這個,你傳遞活動的背景下,不應用程序上下文。對話框不能使用applicationcontext顯示。

+0

他沒有爲dialog.builder構造函數使用'context.getApplicationContext()'表示法。他只是用它來從他的資源拉弦。 (當然,getApplicationContext()有更好的方法),但是這個註釋與顯示的實際對話無關。 – FoamyGuy

+0

對不起@FoamyGuy ......我糾正了。 –