如果尝试从onActivityResult显示对话框,则出现IllegalStateException

时间:2013-08-18 06:58:48

标签: android illegalstateexception android-bluetooth onactivityresult

我正在开发一个需要用户启用蓝牙的应用程序。为此,一旦点击了所需的按钮,就会抛出一个意图来启用蓝牙。我使用以下代码:

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。在其他地方,它按预期显示。

感谢。

1 个答案:

答案 0 :(得分:1)

将Dialog的show-call推迟到FragmentActivity#onResumeFragments()或Activity#onPostResume()而不是onActivityResult

这在"Failure Delivering Result " - onActivityForResult

中得到了解答

完整说明: http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html