首页 > 解决方案 > onActivityResult() 之后的错误结果代码以启用蓝牙和发现

问题描述

我有一项活动要求启用蓝牙和发现模式。请求被正确执行并被onactivityresult(). 问题出在发现请求中。

如果我点击拒绝,那么RESULT_CANCELED是正确的,而如果我点击允许,结果代码是 120,因此它不是RESULT_OK,我无法启动活动,它是 120 而不是正常RESULT_OK吗?

我的活动

public class TransitionActivity extends AppCompatActivity {
    private static final int ENABLE_REQUEST = 0;
    private static final int DISCOVER_REQUEST = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transition);

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(bluetoothAdapter == null){ //bluetooth not supported
            Toast.makeText(this, "Bluetooth not supported.", Toast.LENGTH_SHORT).show();
            finish();
        }

        if(!bluetoothAdapter.isEnabled()){
            Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(i,ENABLE_REQUEST);

        }
        if(!bluetoothAdapter.isDiscovering()){
            Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            startActivityForResult(i,DISCOVER_REQUEST);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == ENABLE_REQUEST){
            if(resultCode == RESULT_OK){
            }
            if(resultCode == RESULT_CANCELED){
                Toast.makeText(this, "You need to enable the bluetooth.", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
        if(requestCode == DISCOVER_REQUEST){
            System.out.println("RESULT CODE" + resultCode); //it is 120
            if(resultCode ==  RESULT_OK){ //skipped
                Intent secondActivity = new Intent(this, com.project.secondActivity.class);
                this.startActivity(secondActivity);
            }
            if(resultCode == RESULT_CANCELED){
                finish();
            }
        }
    }
}

标签: androidbluetoothonactivityresult

解决方案


EXTRA_DISCOVERABLE_DURATIONresultCode 的值与Intent 中传递的可发现持续时间相同。默认持续时间为 120。所以没关系。

如果你要开始这样的活动

Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 240);
startActivityForResult(i,DISCOVER_REQUEST);

它将返回 240 作为结果代码。


推荐阅读