onActivityResult()之后错误的结果代码以启用蓝牙和发现

时间:2019-06-21 10:30:40

标签: android bluetooth onactivityresult

我有一个活动,要求启用蓝牙和发现模式。 请求已正确执行,并由onactivityresult()处理。 问题出在发现请求中。

如果我单击拒绝,那么将正确处理RESULT_CANCELED,而如果我单击允许,则结果代码为120,因此不是RESULT_OK并且无法启动活动,这是正常现象是120,而不是RESULT_OK

MyActivity

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();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

resultCode的值与Intent中传递的可发现持续时间EXTRA_DISCOVERABLE_DURATION相同。 默认持续时间是120。就可以了。

如果您要开始这样的活动

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

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