我正在开发一个需要用户启用蓝牙的应用程序。为此,一旦单击所需的按钮,就会引发启用蓝牙的意图。我正在使用以下代码:
public static final int ENABLE_BT = 1;
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
BluetoothAdapter mAdapter = BluetoothAdapter
.getDefaultAdapter();
if (!mAdapter.isEnabled()) {
Intent enableBTIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(enableBTIntent, ENABLE_BT);
}
}
});
此外,如果用户不启用蓝牙,我希望显示一个对话框。这个类如下:
public class MessageDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please enable Bluetooth to proceed")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// TODO Auto-generated method stub
}
});
return builder.create();
}
}
onActivityResult()
方法如下:
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == ENABLE_BT)
if (resultCode == Activity.RESULT_CANCELED) {
//button.setText("err");
DialogFragment dialog = new MessageDialog();
dialog.show(getSupportFragmentManager(), "Warning !");
}
}
问题是,一旦我不启用蓝牙,应用程序就会以 and 终止IllegalStateException
。日志相关日志为:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {com.iskh.btchat.start/com.iskh.btchat.start.FirstActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
我无法理解如何显示Dialog
是非法的。我已经检查过了,这个错误只有在显示的代码存在时Dialog
才会出现。如果该代码被注释掉,那么应用程序将按预期运行。而且我还测试了Dialog
. 在其他地方,它按预期显示。
谢谢。