如何等到onActivityResult结束?

时间:2016-03-04 00:33:45

标签: android android-fragments android-bluetooth background-thread startactivityforresult

如果用户不批准通过此代码请求激活蓝牙,我有一个不应该打开的片段

    Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        mIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 240);
            startActivityForResult(mIntent, 1);
    //Here I want to exit the method in case result is denied
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.content,new ServerFragment()).addToBackStack(null).commit();

我一直在寻找很多地方,我发现的唯一一件事是使用新活动中的setResult(在我的情况下,onActivityResult在调用活动中被覆盖,因为此代码在片段内)

有什么想法吗?

谢谢!

编辑:这是一个堆栈跟踪

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131073, result=240, data=null} to activity {bt.bt/bt.bt.MainActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
                                                                               at android.app.ActivityThread.deliverResults(ActivityThread.java:3659)
                                                                               at android.app.ActivityThread.handleSendResult(ActivityThread.java:3702)
                                                                               at android.app.ActivityThread.access$1300(ActivityThread.java:155)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:135)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
                                                                            Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

3 个答案:

答案 0 :(得分:0)

您应该在启动意图后返回您的函数。然后等待onActivityResult中的回调。在这个方法中,如果结果是RESULT_OK,那么你将开始你的片段。

    char speechMk = '"';
    QString boundary = "----------------------------123456789abc";

    QByteArray data(QString("--" + boundary + "\r\n").toLatin1());

    data.append(QString("Content-Disposition: form-data; name=" + QString(speechMk) + "api_user" + QString(speechMk) + "\r\n").toLatin1());
    data.append("\r\n");
    data.append("myuser");
    data.append("\r\n");

    data.append("--" + boundary + "\r\n");
    data.append("Content-Disposition: form-data; name=" + QString(speechMk) + "api_key" + QString(speechMk) + "\r\n" );
    data.append("\r\n");
    data.append("mypassword");
    data.append("\r\n");

    data.append("--" + boundary + "\r\n");
    data.append("Content-Disposition: form-data; name=" + QString(speechMk) + "to" + QString(speechMk) + "\r\n");
    data.append("\r\n");
    data.append("myemail@hotmail.co.uk");
    data.append("\r\n");

    data.append("--" + boundary + "\r\n");
    data.append("Content-Disposition: form-data; name=" + QString(speechMk) + "toname" + QString(speechMk) + "\r\n");
    data.append("\r\n");
    data.append( "Destination");
    data.append("\r\n");

    data.append("--" + boundary + "\r\n");
    data.append("Content-Disposition: form-data; name=" + QString(speechMk) + "subject" + QString(speechMk) + "\r\n");
    data.append("\r\n");
    data.append("eSubject");
    data.append("\r\n");

    data.append("--" + boundary + "\r\n");
    data.append("Content-Disposition: form-data; name=" + QString(speechMk) + "text" + QString(speechMk) + "\r\n");
    data.append("\r\n");
    data.append("eBody");
    data.append("\r\n");

    data.append("--" + boundary + "\r\n");
    data.append("Content-Disposition: form-data; name=" + QString(speechMk) + "from" + QString(speechMk) + "\r\n");
    data.append("\r\n");
    data.append("noreply@randomdomain.com");
    data.append("\r\n");

    data.append("--" + boundary + "\r\n");
    data.append("Content-Disposition: form-data; name=" +  QString(speechMk) + "files[1]" + QString(speechMk) + "; filename=" + QString(speechMk) + "TodayRoute.html" + QString(speechMk) + "\r\n");

    data.append("Content-Type: application/octet-stream");
    data.append("\r\n");
    data.append("\r\n");

    QFile file1(path);
    if (!file1.open(QFile::ReadOnly)){
        qDebug() << "could not open";
    } else {
        data.append(file1.readAll().toBase64() + "\r\n");
    }
    data.append("--" + boundary + "--\r\n");

    file1.close();

    QNetworkAccessManager theMan;

    QNetworkRequest req = QNetworkRequest(QUrl("https://api.sendgrid.com/api/mail.send.json"));
    req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("multipart/form-data; boundary=" + boundary));
    theMan.post(req,data);

完整活动:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == your_request_code_here) {
        if (resultCode != Activity.RESULT_CANCELED) {
            // start fragment
        }
    }
}

答案 1 :(得分:0)

与您粘贴的代码一样,只要您调用startActivityForResult(),即表示您不需要这样做,就会实例化该片段 - 这会导致问题。您只需startActivityForResult(),然后在活动的onActivityResult()方法中,如果resultCode为RESULT_OK

,您可以实例化您的片段
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == your_request_code_here) {
        if (resultCode == Activity.RESULT_OK) {

getSupportFragmentManager().beginTransaction().replace(R.id.content,new ServerFragment()).addToBackStack(null).commit();
        }
    }
}

答案 2 :(得分:0)

我认为您应该使用BroadcastReceiver来注册蓝牙事件。 在Manifest.xml中,您需要添加两个语句:

<uses-permission android:name="android.permission.BLUETOOTH" />
<receiver android:name=".BluetoothBroadcastReceiver"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
 </intent-filter>
    </receiver>

然后你需要实现onReceive()方法:

public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    Log.d("BroadcastActions", "Action "+action+"received");
    int state;
    BluetoothDevice bluetoothDevice;

    switch(action)
    {
        case BluetoothAdapter.ACTION_STATE_CHANGED:
            state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            if (state == BluetoothAdapter.STATE_OFF)
            {
                Toast.makeText(context, "Bluetooth is off", Toast.LENGTH_SHORT).show();
                Log.d("BroadcastActions", "Bluetooth is off");
            }
            else if (state == BluetoothAdapter.STATE_TURNING_OFF)
            {
                Toast.makeText(context, "Bluetooth is turning off", Toast.LENGTH_SHORT).show();
                Log.d("BroadcastActions", "Bluetooth is turning off");
            }
            else if(state == BluetoothAdapter.STATE_ON)
            {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.content,new ServerFragment()).addToBackStack(null).commit();
                Log.d("BroadcastActions", "Bluetooth is on");
            }
            break;

....
}

您可以在此链接中看到更多内容:Android Broadcast Receiver bluetooth events catching