我正在尝试在 BluetoothChatService 中添加一个对话框,如果无法建立或丢失连接,它将提示重试蓝牙连接。执行 AlertDialog.show() 时出现运行时异常;此错误发生在 Handler.java 中,错误为“无法在未调用 Looper.prepare() 的线程内创建处理程序”并且 mLooper 为空。我尝试过在 stackoverflow 上找到的其他解决方案,例如 'new AlertDialog.Builder(Activity.this)'; 没有任何效果。
编辑:似乎线程中的对话方法是问题所在。我将在创建线程的 UI Activity 的约束内重新编码对话框。感谢所有回复。
编码:
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();
}
}