How to use onActivityResult when there is more than one startActivityForResult

Asked

Viewed 5,290 times

2

I need to check user status yes or in the, when requesting bluetooth. Only I already use the same method for voice recognition.

Just follow my code:

package com.example.audio_auto;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class AudioActivity extends Activity{

    public Set<BluetoothDevice> pairedDevices;
    private final static int VOICE_RESULT = 1;
    protected static final int Request_Enable_bt = 0;
    private ImageButton btnSpeack;
    private Button btSair, connect, enviar;
    private TextView txtText, txt;
    volatile boolean stopWorker;
    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    private static final String TAG = "QuickNotesMainActivity"; 
    BluetoothDevice mDevice;// cria uma conecao com o dispositivo e consulta.
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mSocket; // gerencia a conexao
    Thread workerThread;
    OutputStream mOutputStream;
    InputStream mInputStream;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio);

        enviar = (Button) findViewById(R.id.button2);
        connect = (Button) findViewById(R.id.button3);
        btSair = (Button) findViewById(R.id.button4);
        btnSpeack = (ImageButton) findViewById(R.id.imageButton1);
        txtText = (TextView) findViewById(R.id.textView1);
        txt = (TextView) findViewById(R.id.textView2);



        btnSpeack.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                        "Favor falar no microfone");

                try {

                    startActivityForResult(intent, VOICE_RESULT);
                    txtText.setTextColor(Color.BLUE);
                    txtText.setText("");
                    // verifica();

                } catch (ActivityNotFoundException e) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "nao suporta seu dispositivo", Toast.LENGTH_LONG);
                    t.show();
                }

            }

        });

        btSair.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                try {
                    closeBT();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }

            private void closeBT()throws IOException{
                stopWorker = true;
                mOutputStream.close();
                mInputStream.close();
                mSocket.close();

            }
        });

        connect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    if(mBluetoothAdapter == null){

                        Toast.makeText(getApplicationContext(), "nao tem suporte bluetooth", Toast.LENGTH_LONG).show();
                    }
            if(!mBluetoothAdapter.isEnabled()){

                    tornaVisivel();
                    Log.i(TAG,"nao espera o resultado!");

            }

            else 
                Toast.makeText(getApplicationContext(), "O bluetooth esta conectado!", Toast.LENGTH_LONG).show();

            }   

        });


        enviar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        });
    }

    protected void tornaVisivel() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();                                                                     
        Intent enableBluetooth = new Intent(
         BluetoothAdapter.ACTION_REQUEST_ENABLE); // emite um pedido para ativar bluetooth
          startActivityForResult(enableBluetooth, 0);

    }

    protected void Conectar() {

        if (mBluetoothAdapter.isEnabled()){ // verifica se esta abilitado
            Log.i(TAG," bluetooth!");
            pairedDevices = mBluetoothAdapter.getBondedDevices(); //checando a lista de aparelhos emparelhados              
            Log.i(TAG,"Found [" + pairedDevices.size() + "] devices."); 
            if (pairedDevices.size() > 0) { // se tiver lista de aparelhos emparelhados
                Log.i(TAG,"pareou");
                for (BluetoothDevice device : pairedDevices) { // atribui as lista de aparelhos pareados no device do tipo BluetoothDevice
                    if (device.getName().equals("SL4 professional")) // pega o nome do dispositivo bluetooth e compara com a string
                    {
                        Log.i(TAG,"ok bluetooth!");
                        mDevice = device; //atribui o nome comparado com a string e coloca em mDevice
                        break;
                    }
                }
            }
        }
    }
/////////////////////////////////////
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == BT_ATIVAR){
      if (RESULT_OK == resultCode){
        // SIM
      } else {
        // NÃO
      }
    }
 }


//////////////////////////////////////  

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

        if (requestCode == VOICE_RESULT && resultCode == RESULT_OK) {
            ArrayList<String> matches = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            txtText.setText(matches.get(0).toString());
        }

        super.onActivityResult(requestCode, resultCode, data);

        String[] confirmar = { "bola", "dado" };

        for (int i = 0; i < confirmar.length; i++) {

            if (txtText.getText().toString().contains(confirmar[i])) {

                txt.setTextColor(Color.GREEN);
                txt.setText("Comando Conhecido");
                break;
            } else {
                txt.setTextColor(Color.RED);
                txt.setText("Comando Desconhecido !");
            }

        }
    }
}
  • I don’t understand any of your question. What is your problem?

  • if that’s what I understand, "Polymorphism" research. I think that’s what you want.

  • then I have two ways onActivityResult () my app when it asks for bluetooth activation by the user I need to know if it clikou yes or no for me to continue in my app only that for me to know this by the documentation the result goes to this method "onActivityResult()" only I’m already using it for the voice command just below and so gives the error methodDuplicate ! got it ?

  • Another personal thing has some tutorial explaining how to format the questions and Cod ! because when put here any doubt, everything is without format ! I think someone from you will fix it so it looks nice .. Thank you.

  • Behold here how to format publications

  • worth ramaral now this formatted right...

Show 1 more comment

2 answers

4


There can only be one method onActivityResult() in each Activity.

This method is called after each call to startActivityForResult.
When calling the method startActivityForResult is passed, in the second parameter, a requestCode.

That one requestCode is received in the method onActivityResult().
Just check which one requestCode and act accordingly.

Looking at your code, you use VOICE_RESULT to the requestCode when you use RecognizerIntent.ACTION_RECOGNIZE_SPEECH and 0 when you use the BluetoothAdapter.ACTION_REQUEST_ENABLE.

Thus, your method onActivityResult should be something like:

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

    if (requestCode == VOICE_RESULT && resultCode == RESULT_OK) {

       //Fazer o que pretende quando retorna do Voice
    }
    if (requestCode == 0 && resultCode == RESULT_OK) {
        //Fazer o que pretende quando retorna do Bluetooth
    }
}

Instead of 0 use the Request_enable_bt constant, set at the beginning of the code, for the requestCode bluetooth

0

Thank you Ramaral ! I actually noticed this before you post but it was exactly what I did valeu mano solved my problem and the best my doubt (that can only once this method ) follows my Cod:

package com.example.audio_auto;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class AudioActivity extends Activity{    
public Set<BluetoothDevice> pairedDevices;
private final static int VOICE_RESULT = 1;
protected static final int Request_Enable_bt = 0;
private ImageButton btnSpeack;
private Button btSair, connect, enviar;
private TextView txtText, txt;
volatile boolean stopWorker;
byte[] readBuffer;
int readBufferPosition;
int counter;
private static final String TAG = "QuickNotesMainActivity"; 
BluetoothDevice mDevice;// cria uma conecao com o dispositivo e consulta.
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mSocket; // gerencia a conexao
Thread workerThread;
OutputStream mOutputStream;
InputStream mInputStream;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio);
    enviar = (Button) findViewById(R.id.button2);
    connect = (Button) findViewById(R.id.button3);
    btSair = (Button) findViewById(R.id.button4);
    btnSpeack = (ImageButton) findViewById(R.id.imageButton1);
    txtText = (TextView) findViewById(R.id.textView1);
    txt = (TextView) findViewById(R.id.textView2);

    btnSpeack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(
                    RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
                    "Favor falar no microfone");

            try {

                startActivityForResult(intent, VOICE_RESULT);
                txtText.setTextColor(Color.BLUE);
                txtText.setText("");
                // verifica();

            } catch (ActivityNotFoundException e) {
                Toast t = Toast.makeText(getApplicationContext(),
                        "nao suporta seu dispositivo", Toast.LENGTH_LONG);
                t.show();
            }

        }

    });

    btSair.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            try {
                closeBT();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        private void closeBT()throws IOException{
            stopWorker = true;
            mOutputStream.close();
            mInputStream.close();
            mSocket.close();            
        }
    });

    connect.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

             mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if(mBluetoothAdapter == null){

                    Toast.makeText(getApplicationContext(), "nao tem suporte bluetooth", Toast.LENGTH_LONG).show();
                }
        if(!mBluetoothAdapter.isEnabled()){

                tornaVisivel();
                Log.i(TAG,"nao espera o resultado!");               
        }

        else 
            Toast.makeText(getApplicationContext(), "O bluetooth esta conectado!", Toast.LENGTH_LONG).show();

        }   

    });


    enviar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });
}

protected void tornaVisivel() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();                                                                     
    Intent enableBluetooth = new Intent(
     BluetoothAdapter.ACTION_REQUEST_ENABLE); // emite um pedido para ativar bluetooth
      startActivityForResult(enableBluetooth, 0);

}

protected void Conectar() {

    if (mBluetoothAdapter.isEnabled()){ // verifica se esta abilitado
        Log.i(TAG," bluetooth!");
        pairedDevices = mBluetoothAdapter.getBondedDevices(); //checando a lista de aparelhos emparelhados              
        Log.i(TAG,"Found [" + pairedDevices.size() + "] devices."); 
        if (pairedDevices.size() > 0) { // se tiver lista de aparelhos emparelhados
            Log.i(TAG,"pareou");
            for (BluetoothDevice device : pairedDevices) { // atribui as lista de aparelhos pareados no device do tipo BluetoothDevice
                if (device.getName().equals("SL4 professional")) // pega o nome do dispositivo bluetooth e compara com a string
                {
                    Log.i(TAG,"ok bluetooth!");
                    mDevice = device; //atribui o nome comparado com a string e coloca em mDevice
                    break;
                }
            }
        }
    }
}


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

    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

    case 0:

              if (RESULT_OK == resultCode){
           Log.i(TAG,"sim ativo");
              } else {
            Log.i(TAG,"nao ativo");
              }

        break;// break 0

    case 1:
        if (resultCode == RESULT_OK){
            ArrayList<String> matches = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            txtText.setText(matches.get(0).toString());

        String[] confirmar = { "bola", "dado" };

        for (int i = 0; i < confirmar.length; i++) {

            if (txtText.getText().toString().contains(confirmar[i])) {

                txt.setTextColor(Color.GREEN);
                txt.setText("Comando Conhecido");
                break;
            } else {
                txt.setTextColor(Color.RED);
                txt.setText("Comando Desconhecido !");
            }
         }
        }
        break;// break 1    
    }

 }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.