Wait until the onActivityResult Callback

0

I have a problem checking the result of the callback, when I call onActivityResult () to get the result if the user allowed or canceled the activation of bluetooth, the program does not wait for the result of the user's decision.

I need you to wait for the answer so that I can ask in the If correctly.

public void iniciarBluetooth(){
    if(localBT == null){
        Log.d(TAG, "iniciarBlueetooth: El dispositivo no cuenta con blueetoth integrado");
    }else if(!localBT.isEnabled()){
        Log.d(TAG, "iniciarBlueetooth: iniciando bluetooth");


        Intent iniciarBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(iniciarBluetoothIntent, REQUEST_ENABLE_BT);

        int resultado = 0;
        onActivityResult(REQUEST_ENABLE_BT, resultado, iniciarBluetoothIntent);

        if(resultado == RESULT_OK) {
            Log.d(TAG, "iniciarBlueetooth: Se encendera el bluetooth");
            switchBT.setText(getString(R.string.apagarBT));
        }else
            Log.d(TAG, "iniciarBlueetooth: Se cancelo la solicitud de encendido bluetooth");

    }else if(localBT.isEnabled()){
        Log.d(TAG, "iniciarBlueetooth: apagando bluetooth");
        localBT.disable();

        switchBT.setText(getString(R.string.encenderBT));
    }
}

Logcat response

/com.example.refer.bluetooth D/MainActivity: iniciarBlueetooth: iniciando bluetooth
//No espera el resultado del callback y comprueba con el valor de inicializacion del Int resultado
/com.example.refer.bluetooth D/MainActivity: iniciarBlueetooth: Se cancelo la solicitud de encendido bluetooth
    
asked by Asahi Sara 26.06.2017 в 02:02
source

1 answer

1

This is not how you use a callback, you need two methods, the one you already have to start the activity, and another that will be the callback, something like this:

public void iniciarBluetooth(){
    if(localBT == null){
        Log.d(TAG, "iniciarBlueetooth: El dispositivo no cuenta con blueetoth integrado");
    }else if(!localBT.isEnabled()){
        Log.d(TAG, "iniciarBlueetooth: iniciando bluetooth");

        Intent iniciarBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(iniciarBluetoothIntent, REQUEST_ENABLE_BT);

    }else if(localBT.isEnabled()){
        Log.d(TAG, "iniciarBlueetooth: apagando bluetooth");
        localBT.disable();

        switchBT.setText(getString(R.string.encenderBT));
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(resultCode == RESULT_OK) {
        Log.d(TAG, "iniciarBlueetooth: Se encendera el bluetooth");
        switchBT.setText(getString(R.string.apagarBT));
    }else
        Log.d(TAG, "iniciarBlueetooth: Se cancelo la solicitud de encendido bluetooth");

}

I recommend you study a bit and see what a callback is: link [English]

    
answered by 26.06.2017 / 08:13
source