我正在开发一个需要用户启用蓝牙的应用程序。为此,一旦单击了所需的按钮,就会引发启用蓝牙的意图。我正在使用以下代码:
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 !");
}
}
问题是,一旦我不启用蓝牙,应用程序就会以和
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
。在其他地方按预期显示。谢谢。
最佳答案
将对话框的显示调用推迟到FragmentActivity#onResumeFragments()或Activity#onPostResume()而不是onActivityResult
在"Failure Delivering Result " - onActivityForResult中回答
完整说明:
http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html
关于android - 如果尝试从onActivityResult显示对话框,则抛出IllegalStateException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18296540/