2012-09-04 4 views
0

연결을 만들 수 없거나 연결이 끊어진 경우 블루투스 연결을 다시 시도할지 묻는 대화 상자를 BluetoothChatService에 추가하려고합니다. AlertDialog.show()가 실행될 때 런타임 예외가 발생합니다. 이 오류는 Handler.java에서 "Looper.prepare()"를 호출하지 않은 스레드 내부에서 핸들러를 만들 수 없으며 mLooper가 null 인 오류와 함께 발생합니다. 'new AlertDialog.Builder (Activity.this)'와 같이 stackoverflow에서 찾은 다른 솔루션을 사용해 보았습니다. 아무것도 효과가 없습니다.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 ... 나는 고쳤습니다. –

관련 문제