How to use onActivityResult when there is more than one startActivityForResult

2

I need to check the status of user yes or in when requesting bluetooth. But I already use the same method for speech recognition.

Here is 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 !");
            }

        }
    }
}
    
asked by anonymous 14.02.2015 / 19:06

2 answers

4

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

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

This requestCode is received in the onActivityResult() method. Just check what that requestCode is and act accordingly.

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

So, your onActivityResult method should be anything 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, defined at the beginning of the code, for Bluetooth requestCode     

14.02.2015 / 22:41
0

Thank you Ramaral! in fact I realized this before you post but it was exactly what I did, thanks, my problem solved my problem and the best my doubt (that only can 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    
    }

 }
}
    
14.02.2015 / 23:05