Pass a variable from public void OnCreate - android

I wanted to know how can I pass a variable from private void to OnCreate?
public final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
int k=Integer.parseInt(readMessage.replaceAll("[\\D]",""));
mConversationArrayAdapter.add(readMessage);
Toast.makeText(getApplicationContext(),"ciao"+k ,Toast.LENGTH_SHORT).show();
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
This is OnCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mvc = (Button) findViewById(R.id.button1);
mvc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
public void run() {
while (progressStatus < 1000) {
Random r = new Random();
int i1 = r.nextInt(1000);
if (i1 > progressStatus){
progressStatus = i1;
}
else {
progressStatus = progressStatus;
}
// Update the progress bar and display the current value in the text view
handler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressStatus);
}
});
try {
// Sleep for 200 milliseconds. Just to display the progress slowly
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
res = (Button) findViewById(R.id.button2);
res.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressBar.setProgress(0);
progressStatus=0;
}
});
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
I pass the variable k, is there a method? or I have to go to a public int? I do not know how to solve. Thank you in advance!

Umm, why not make k a Global Variable?
Add int k inside starting of your class
For example :
...
public class MainActivity extends Activity {
int k;
//onCreate and other methods
}
...
Change
int k = =Integer.parseInt (readMessage.replaceAll.replaceAll("[\\D]",""));
to
k = =Integer.parseInt(readMessage.replaceAll.replaceAll("[\\D]",""));
as you've already made k an integer.
Then you can use k anywhere in your class

Related

Restart SpeechRecognizer using onUtteranceProgressListener

I've been working on this code for weeks with no progress at all, even though it seems like such an easy fix!! Basically I am using TextToSpeech with SpeechRecognizer in order to have the app ask me a question and then listen for my answer. Here's my code... I'm thinking its a thread problem or something.
Basically when I hold down the button, SPeechRecognizer starts listening until i take away finger... this works fine.. but I programmatically want the SpeechRecognizer to start up again after Utterance is Completed or simulate a button press to get it to work but neither works...
public class MainActivity extends AppCompatActivity {
TextToSpeech textToSpeech;
// SpeechRecognizer
SpeechRecognizer mSpeechRecognizer;
Intent mSpeechRecognizerIntent;
// Speech Analysis Support
SpeechToTextAnalyzer speechToTextAnalyzer;
String speechToTextAnalyzerResponse;
String SPEECH_RESPONSE_BACK;
int buttonPressCounter;
boolean responsive;
TextView StatusDisplay, WordingDisplay;
Button SimulateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
buttonPressCounter = 0;
// Initialize TextToSpeech
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
}
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
// Speaking started.
}
#Override
public void onDone(String utteranceId) {
// Speaking stopped.
if(responsive){ // if(utteranceId == "LISTEN_FOR_NEW_RESPONSE")
// possible method one:
SimulateButton.performClick();
// possible method two:
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
// NOTE: SO FAR NEITHER OF THESE LINES MAKE THE SPEECHRECOGNIZER START UP WITHOUT ME TOUCHING THE BUTTON!!!
}
}
#Override
public void onError(String utteranceId) {
// There was an error.
}
});
}
});
// Initialize UI View Components
StatusDisplay = (TextView)findViewById(R.id.StatusUpdater);
WordingDisplay = (TextView)findViewById(R.id.WordsHeard);
// Create Reference to Classes
speechToTextAnalyzer = new SpeechToTextAnalyzer(this, this);
// Initialize SpeechRecognizer and Intent
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int errorCode) {
String errorMessage = getErrorText(errorCode);
//Log.d(LOG_TAG, "FAILED " + errorMessage);
//listeningOn = false; // UNSURE!!
}
// accompanying text for onError
public String getErrorText(int errorCode) {
String message;
switch (errorCode) {
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio Recording Error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client Side Error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient Permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network Error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network TimeOut";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No Match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService Busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "Error From Server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No Speech Input";
break;
default:
message = "Couldn't Understand, Please Try Again";
break;
}
return message;
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String firstMatch = "";
//displaying the first match
if (matches != null) {
for(int i = 0; i < matches.size(); i++){
firstMatch = matches.get(i); // get the last one, which has the actual words I spoke...
}
matches.clear();
}
//StatusDisplay.setText("Not Listening...");
// ENTRY POINT FOR ALL COMMAND FUNCTIONALITY
speechToTextAnalyzerResponse = speechToTextAnalyzer.AnalyzeSpeechSingleResponse(firstMatch);
buttonPressCounter = speechToTextAnalyzer.AnalyzeSpeechCounter(buttonPressCounter);
responsive = speechToTextAnalyzer.AnalyzeSpeechResponseThenListen(buttonPressCounter);
SPEECH_RESPONSE_BACK = speechToTextAnalyzerResponse;
WordingDisplay.setText(SPEECH_RESPONSE_BACK);
if(responsive){
RESPONSIVE_SPEECH("... okay now say something new ... ");
}
else {
SINGLE_RESPONSE();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
}); // end of mSpeechRecognizer.setRecognitionListener
SimulateButton = (Button)findViewById(R.id.DoSomething);
SimulateButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
//when the user removed the finger
mSpeechRecognizer.stopListening();
StatusDisplay.setText("Not Listening...");
break;
case MotionEvent.ACTION_DOWN:
//finger is on the button
StatusDisplay.setText("Listening...");
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
// WHILE I HOLD BUTTON THIS ACTUALLY WORKS BUT NOT INSIDE ONUTTERANCEPROGRESSLISTENER.........
break;
}
return true;
}
});
} // end of onCreate()
public void SINGLE_RESPONSE(){
if (!textToSpeech.isSpeaking()) {
textToSpeech.speak(SPEECH_RESPONSE_BACK, TextToSpeech.QUEUE_FLUSH, null);
//textToSpeech.speak(WordingDisplay.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
} else {
textToSpeech.stop();
}
}
public void RESPONSIVE_SPEECH(String PleaseSayThis){
SPEECH_RESPONSE_BACK = PleaseSayThis;
// https://android-developers.googleblog.com/2009/09/introduction-to-text-to-speech-in.html
if (!textToSpeech.isSpeaking()) {
HashMap<String, String> stringStringHashMap = new HashMap<String, String>();
stringStringHashMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "LISTEN_FOR_NEW_RESPONSE"); // when using normal text to speech, the ID is "ID_MAIN_CALL" to be searched for in onUtteranceCompleted
textToSpeech.speak(SPEECH_RESPONSE_BACK, textToSpeech.QUEUE_FLUSH, stringStringHashMap);
} else {
textToSpeech.stop();
}
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
protected void onDestroy(){
if(textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
textToSpeech = null;
}
super.onDestroy();
}
According to the UtteranceProgressListener docs, "The callbacks specified in this method can be called from multiple threads."
To verify this, you can add
boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
Log.i("XXX", "was onDone() called on a background thread? : " + wasCalledFromBackgroundThread);
to the onDone() method body.
In my experience, they are called on background threads more often than not.
So, inside your onDone() method body, I would suggest surrounding the UI manipulation with runOnUiThread() like so:
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// possible method one:
SimulateButton.performClick();
// possible method two:
//mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
});
}

SpeechRecognizer on Android 7.0

I've implemented a SpeechRecognizer, and it's working perfectly on Android 6, but its not working on android 7.0, I don't know why.
If I try to use the recognizer on startActivityforResult(), it work's perfectly, but if I use createListener method, nothing happens, even I tried to output all results.
Here is my code :
class listener implements RecognitionListener
{
String TAG = "AFFICHAGE";
public void onReadyForSpeech(Bundle params)
{
Toast.makeText(MainActivity.this,"READY TO LISTEN", Toast.LENGTH_LONG).show();
}
public void onBeginningOfSpeech()
{
}
public void onRmsChanged(float rmsdB)
{
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
switch (error){
case SpeechRecognizer.ERROR_AUDIO:
Toast.makeText(MainActivity.this, "ERROR AUDIO",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_CLIENT:
Toast.makeText(MainActivity.this, "ERROR CLIENT",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
Toast.makeText(MainActivity.this, "ERROR PERMISSION",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_NETWORK:
Toast.makeText(MainActivity.this, "ERROR INTERNET",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
Toast.makeText(MainActivity.this, "ERROR TIMEOUT",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_NO_MATCH:
Toast.makeText(MainActivity.this, "ERROR NO MATCH",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
Toast.makeText(MainActivity.this, "ERROR BUSY",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_SERVER:
Toast.makeText(MainActivity.this, "ERROR SERVER",Toast.LENGTH_LONG).show();
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
Toast.makeText(MainActivity.this, "ERROR TIMEOUT",Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
public void onResults(Bundle results)
{
String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
txtSpeechInput.setText("results: "+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
and here is where I call it :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btn = (Button) findViewById(R.id.button);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
btn.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_CALLING_PACKAGE,"voice.recognition.test");
//intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
}
});
}
Thank for answer.
I've found a solution to make it work on initializiting the google librairie like this : SpeechRecognizer.createSpeechRecognizer(getApplication(), ComponentName.unflattenFromString("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"));
And it's work, so I don't now if it's a good solution or not.

I need some help regarding android Speech Recognizer API

I need some help on conversion of speech to text using Android Speech API. The API is giving me correct results on my Device (Android Version 2.3.5) but when I tested it on Device Having Android Version 4.1.2, it is giving me abnormal results. Like the result is being repeated multiple times. If somebody have faced this problem can you tell me how to cater this issue ?
Following is the code I am using:
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
protected static final String TAG = "MY_TAG";
private TextView spokenText;
private Button spkButton;
private Button stopButton;
private SpeechRecognizer sR;
private ClickListener clickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickListener = new ClickListener();
spokenText = (TextView) findViewById(R.id.spokenText);
spokenAnswer = (TextView) findViewById(R.id.spokenAnswer);
spkButton = (Button) findViewById(R.id.speakButton);
stopButton = (Button) findViewById(R.id.stopButton);
spkButton.setOnClickListener(clickListener);
stopButton.setOnClickListener(clickListener);
sR = SpeechRecognizer.createSpeechRecognizer(this);
sR.setRecognitionListener(new listener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void startListening()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,this.getPackageName());
sR.startListening(intent);
}
public void stopListening()
{
sR.stopListening();
}
class ClickListener implements OnClickListener
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == spkButton)
{
startListening();
}
else if(v == stopButton)
{
stopListening();
}
}
}
class listener implements RecognitionListener{
#Override
public void onRmsChanged(float rmsdB) {
// TODO Auto-generated method stub
//Log.d(TAG, "onRmsChanged");
}
#Override
public void onResults(Bundle results) {
// TODO Auto-generated method stub
String str = new String();
//Log.d(TAG, "onResults " + results);
ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
//Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
Log.d(TAG, str);
spokenText.setText(str);
}
#Override
public void onReadyForSpeech(Bundle params) {
// TODO Auto-generated method stub
//Log.d(TAG, "onReadyForSpeech");
}
#Override
public void onPartialResults(Bundle partialResults) {
// TODO Auto-generated method stub
//Log.d(TAG, "onPartialResults");
}
#Override
public void onEvent(int eventType, Bundle params) {
// TODO Auto-generated method stub
//Log.d(TAG, "onEvent");
}
#Override
public void onError(int error) {
// TODO Auto-generated method stub
String mError = "";
switch (error) {
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
mError = " network timeout";
break;
case SpeechRecognizer.ERROR_NETWORK:
mError = " network" ;
return;
case SpeechRecognizer.ERROR_AUDIO:
mError = " audio";
break;
case SpeechRecognizer.ERROR_SERVER:
mError = " server";
break;
case SpeechRecognizer.ERROR_CLIENT:
mError = " client";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
mError = " speech time out" ;
break;
case SpeechRecognizer.ERROR_NO_MATCH:
mError = " no match" ;
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
mError = " recogniser busy" ;
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
mError = " insufficient permissions" ;
break;
}
//Log.d(TAG, "Error: " + error + " - " + mError);
//startListening();
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
//Log.d(TAG, "onEndOfSpeech");
//startListening();
}
#Override
public void onBufferReceived(byte[] buffer) {
// TODO Auto-generated method stub
//Log.d(TAG, "onBufferReceived");
}
#Override
public void onBeginningOfSpeech() {
// TODO Auto-generated method stub
}
}
}
Following is the output i am seeing - The results are abnormal, it should have shown a single time rather that 3 times ..
Here is a chunk of response from one of the google-speech-api on android. Note the JSON array in the 'hypothesis' field...
{"status":0,"id":"a4ca9654c6cc684dc3279cd1aaa00cc7-1","hypotheses":[{"utterance":"map
of the state of California","confidence":0.87869847}]}
You need to know the details of the api's response body you are using and , if necessary , how to parse JSON arrays in the response like the 'hypothesis' field above.
If it is an array as i suspect it is , then you just need a little parsing of the array to get the proper response without the duplication issue.

How do I executed a function for specific seconds

So basically, I want to stream data from bluetooth but with on-off mode. Each on & off mode happened for a specific amount of time, i.e 5 seconds.
So,
I need to put a function to executed for a 5 seconds and then executed another function inside a button click method. But my code below doesn't work as it should be.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.btnOn); // button LED ON
btnOff = (Button) findViewById(R.id.btnOff); // button LED OFF
btnStart = (Button) findViewById(R.id.btnStart);
txtArduino = (TextView) findViewById(R.id.txtArduino); // for display the received data from the Arduino
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
btnOff.setEnabled(true);
btnOn.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btnOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOn.setEnabled(false);
bluetoothConnect();
}
});
btnOff.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnOff.setEnabled(false);
bluetoothDisconnect();
}
});
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
bluetoothDisconnect();
//Starts from here the code doesn't work
//I want to perform these functions over and over
while (true){
//I want method executed for 5 seconds here
h.postDelayed(new Runnable() {
#Override
public void run(){
bluetoothConnect();
}
}, 5000);
//I want method executed for 5 seconds here
h.postDelayed(new Runnable() {
#Override
public void run(){
bluetoothDisconnect();
}
}, 5000);
}
}
});
}
You can try the following way...
private boolean canExecute;
private void callYourMethod() {
canExecute = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
canExecute = false;
}
}, 5000);
yourMethodToExecuteForFiveSeconds();
}
private void yourMethodToExecuteForFiveSeconds() {
// Your code goes here
if (canExecute) {
//This will be true for five seconds only.
yourMethodToExecuteForFiveSeconds();
}
}

Result activity closes main activity when pressing back button

I'm developing an app, where I have a button wich displays a dialog Activity where it finds bluetooth devices.
It works fine, but if I press de back button while in this activity, instead of returning to the main activity, it destroys it.
The dialog activity is the same that in the BluetoothChat example. This is the code of the main activity:
/*********************
*
* ONCREATE
*
********************/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
/**Call to the Configuration activity*/
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lanzarConfiguracion (null);
}
});
/**Call to the DeviceList activity*/
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
lanzarBusqueda (null);
}
});
GlobalVar.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (GlobalVar.mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
/*********************
*
* ONSTART
*
********************/
#Override
public void onStart() {
super.onStart();
if (!GlobalVar.mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, GlobalVar.REQUEST_ENABLE_BT);
}
else {
if (GlobalVar.mTransmission == null) setupCaller();
}
}
/*********************
*
* ONDESTROY
*
********************/
#Override
public void onDestroy() {
super.onDestroy();
/**Stop the Bluetooth chat services*/
if (GlobalVar.mTransmission != null) GlobalVar.mTransmission.stop();
}
/*********************
*
* OPTIONS
*
********************/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/**Inflate the menu; this adds items to the action bar if it is present.*/
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.info:
lanzarInfo(null);
break;
case R.id.config:
lanzarConfiguracion(null);
break;
}
return true; /** true -> consumimos el item, no se propaga*/
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case GlobalVar.REQUEST_CONNECT_DEVICE:
/**When DeviceListActivity returns with a device to connect*/
if (resultCode == Activity.RESULT_OK) {
connectDevice(data);
}
case GlobalVar.REQUEST_ENABLE_BT:
/**When the request to enable Bluetooth returns*/
if (resultCode == Activity.RESULT_OK) {
/**Bluetooth is now enabled, so set up a chat session*/
setupCaller();
} else {
/**User did not enable Bluetooth or an error occurred*/
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
private void connectDevice(Intent data) {
/**Get the device MAC address*/
String address = data.getExtras().getString(DeviceListDialog.EXTRA_DEVICE_ADDRESS);
/**Get the BluetoothDevice object*/
BluetoothDevice device = GlobalVar.mBluetoothAdapter.getRemoteDevice(address);
/**Attempt to connect to the device*/
try{
GlobalVar.mTransmission.connect(device);
}catch(Exception ex) {
}
}
private final void setStatus(int resId) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(resId);
}
private final void setStatus(CharSequence subTitle) {
final ActionBar actionBar = getActionBar();
actionBar.setSubtitle(subTitle);
}
/**
* The Handler that gets information back from the Transmission
*/
public final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case GlobalVar.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case GlobalVar.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, GlobalVar.mConnectedDeviceName));
GlobalVar.mCommunicationArrayAdapter.clear();
break;
case GlobalVar.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case GlobalVar.STATE_LISTEN:
case GlobalVar.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case GlobalVar.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
/**construct a string from the buffer*/
String writeMessage = new String(writeBuf);
GlobalVar.mCommunicationArrayAdapter.add("Me: " + writeMessage);
break;
case GlobalVar.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
/**construct a string from the valid bytes in the buffer*/
String readMessage = new String(readBuf, 0, msg.arg1);
GlobalVar.mCommunicationArrayAdapter.add(GlobalVar.mConnectedDeviceName+": " + readMessage);
break;
case GlobalVar.MESSAGE_DEVICE_NAME:
/**save the connected device's name*/
GlobalVar.mConnectedDeviceName = msg.getData().getString(GlobalVar.DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to " + GlobalVar.mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case GlobalVar.MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(GlobalVar.TOAST), Toast.LENGTH_SHORT).show();
break;
}
}
};
public void setupCaller() {
/**Initialize the Transmission to perform bluetooth connections*/
GlobalVar.mTransmission = new Transmission(this, mHandler);
/**Initialize the array adapter here for avoid errors with the Handler above*/
//GlobalVar.mCommunicationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
}
/*********************
*
* INTENTS
*
********************/
public void lanzarConfiguracion (View view) {
Intent i = new Intent (this, Configuration.class);
startActivity(i);
}
public void lanzarInfo (View view) {
Intent i = new Intent(this, Info.class);
startActivity(i);
}
public void lanzarBusqueda (View view) {
Intent serverintent = new Intent(this, DeviceListDialog.class);
startActivityForResult(serverintent, GlobalVar.REQUEST_CONNECT_DEVICE);
}
}
You forgot the break statement before
case GlobalVar.REQUEST_ENABLE_BT:
The execution continues in this case, and reaches the finish() statement because the default RESULT_CODE for back press is Activity.RESULT_CANCEL.

Categories

Resources