Google Speech to Text dialog stuck - android

I am developing an app in which I want to use transliteration from Hindi to English via speech input. for that, I am using google STT API. Everything works when my voice input is short, but when I give long voice input, Dialog gets stuck at "Try Saying Something..." and I don't get results a well.
This is my Main Activity:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original and recognized Text
TextView Original,result;
// Request Code for STT
private final int SST_REQUEST_CODE = 101;
// Conversion Table Object...
ConversionTable conversionTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
result = findViewById(R.id.Recognized_Text);
RecordBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// For 30 Sec it will Record...
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Off line Recognition Engine only...
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
// Use Hindi Speech Recognition Model...
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
try {
startActivityForResult(intent, SST_REQUEST_CODE);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.error),
Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SST_REQUEST_CODE:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> getResult = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Original.setText(getResult.get(0));
conversionTable = new ConversionTable();
String Transformed_String = conversionTable.transform(getResult.get(0));
result.setText(Transformed_String);
}
break;
}
}
}
My ConversationTable.class :-
package android.example.com.conversion;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
public class ConversionTable
{
private String TAG = "Conversation Table";
private Hashtable<String,String> unicode;
private void populateHashTable()
{
unicode = new Hashtable<>();
// unicode
unicode.put("\u0901","rha"); // anunAsika - cchandra bindu, using ~ to // *
unicode.put("\u0902","n"); // anusvara
unicode.put("\u0903","ah"); // visarga
unicode.put("\u0940","ee");
unicode.put("\u0941","u");
unicode.put("\u0942","oo");
unicode.put("\u0943","rhi");
unicode.put("\u0944","rhee"); // * = Doubtful Case
unicode.put("\u0945","e");
unicode.put("\u0946","e");
unicode.put("\u0947","e");
unicode.put("\u0948","ai");
unicode.put("\u0949","o");
unicode.put("\u094a","o");
unicode.put("\u094b","o");
unicode.put("\u094c","au");
unicode.put("\u094d","");
unicode.put("\u0950","om");
unicode.put("\u0958","k");
unicode.put("\u0959","kh");
unicode.put("\u095a","gh");
unicode.put("\u095b","z");
unicode.put("\u095c","dh"); // *
unicode.put("\u095d","rh");
unicode.put("\u095e","f");
unicode.put("\u095f","y");
unicode.put("\u0960","ri");
unicode.put("\u0961","lri");
unicode.put("\u0962","lr"); // *
unicode.put("\u0963","lree"); // *
unicode.put("\u093E","aa");
unicode.put("\u093F","i");
// Vowels and Consonants...
unicode.put("\u0905","a");
unicode.put("\u0906","a");
unicode.put("\u0907","i");
unicode.put("\u0908","ee");
unicode.put("\u0909","u");
unicode.put("\u090a","oo");
unicode.put("\u090b","ri");
unicode.put("\u090c","lri"); // *
unicode.put("\u090d","e"); // *
unicode.put("\u090e","e"); // *
unicode.put("\u090f","e");
unicode.put("\u0910","ai");
unicode.put("\u0911","o");
unicode.put("\u0912","o");
unicode.put("\u0913","o");
unicode.put("\u0914","au");
unicode.put("\u0915","k");
unicode.put("\u0916","kh");
unicode.put("\u0917","g");
unicode.put("\u0918","gh");
unicode.put("\u0919","ng");
unicode.put("\u091a","ch");
unicode.put("\u091b","chh");
unicode.put("\u091c","j");
unicode.put("\u091d","jh");
unicode.put("\u091e","ny");
unicode.put("\u091f","t"); // Ta as in Tom
unicode.put("\u0920","th");
unicode.put("\u0921","d"); // Da as in David
unicode.put("\u0922","dh");
unicode.put("\u0923","n");
unicode.put("\u0924","t"); // ta as in tamasha
unicode.put("\u0925","th"); // tha as in thanks
unicode.put("\u0926","d"); // da as in darvaaza
unicode.put("\u0927","dh"); // dha as in dhanusha
unicode.put("\u0928","n");
unicode.put("\u0929","nn");
unicode.put("\u092a","p");
unicode.put("\u092b","ph");
unicode.put("\u092c","b");
unicode.put("\u092d","bh");
unicode.put("\u092e","m");
unicode.put("\u092f","y");
unicode.put("\u0930","r");
unicode.put("\u0931","rr");
unicode.put("\u0932","l");
unicode.put("\u0933","ll"); // the Marathi and Vedic 'L'
unicode.put("\u0934","lll"); // the Marathi and Vedic 'L'
unicode.put("\u0935","v");
unicode.put("\u0936","sh");
unicode.put("\u0937","ss");
unicode.put("\u0938","s");
unicode.put("\u0939","h");
// represent it\
// unicode.put("\u093c","'"); // avagraha using "'"
// unicode.put("\u093d","'"); // avagraha using "'"
unicode.put("\u0969","3"); // 3 equals to pluta
unicode.put("\u014F","Z");// Z equals to upadhamaniya
unicode.put("\u0CF1","V");// V equals to jihvamuliya....but what character have u settled for jihvamuliya
/* unicode.put("\u0950","Ω"); // aum
unicode.put("\u0958","κ"); // Urdu qaif
unicode.put("\u0959","Κ"); //Urdu qhe
unicode.put("\u095A","γ"); // Urdu gain
unicode.put("\u095B","ζ"); //Urdu zal, ze, zoe
unicode.put("\u095E","φ"); // Urdu f
unicode.put("\u095C","δ"); // Hindi 'dh' as in padh
unicode.put("\u095D","Δ"); // hindi dhh*/
unicode.put("\u0926\u093C","τ"); // Urdu dwad
unicode.put("\u0924\u093C","θ"); // Urdu toe
unicode.put("\u0938\u093C","σ"); // Urdu swad, se
}
ConversionTable()
{
populateHashTable();
}
public String transform(String s1)
{
StringBuilder transformed = new StringBuilder();
int strLen = s1.length();
ArrayList<String> shabda = new ArrayList<>();
String lastEntry = "";
for (int i = 0; i < strLen; i++)
{
char c = s1.charAt(i);
String varna = String.valueOf(c);
Log.d(TAG, "transform: " + varna + "\n");
String halant = "0x0951";
if (VowelUtil.isConsonant(varna))
{
Log.d(TAG, "transform: " + unicode.get(varna));
shabda.add(unicode.get(varna));
shabda.add(halant); //halant
lastEntry = halant;
}
else if (VowelUtil.isVowel(varna))
{
Log.d(TAG, "transform: " + "Vowel Detected...");
if (halant.equals(lastEntry))
{
if (varna.equals("a"))
{
shabda.set(shabda.size() - 1,"");
}
else
{
shabda.set(shabda.size() - 1, unicode.get(varna));
}
}
else
{
shabda.add(unicode.get(varna));
}
lastEntry = unicode.get(varna);
} // end of else if is-Vowel
else if (unicode.containsKey(varna))
{
shabda.add(unicode.get(varna));
lastEntry = unicode.get(varna);
}
else
{
shabda.add(varna);
lastEntry = varna;
}
} // end of for
for (String string: shabda)
{
transformed.append(string);
}
//Discard the shabda array
shabda = null;
return transformed.toString(); // return transformed;
}
}
My ViewUtil Class:-
package android.example.com.conversion;
public class VowelUtil {
protected static boolean isVowel(String strVowel) {
// Log.logInfo("came in is_Vowel: Checking whether string is a Vowel");
return strVowel.equals("a") || strVowel.equals("aa") || strVowel.equals("i") || strVowel.equals("ee") ||
strVowel.equals("u") || strVowel.equals("oo") || strVowel.equals("ri") || strVowel.equals("lri") || strVowel.equals("e")
|| strVowel.equals("ai") || strVowel.equals("o") || strVowel.equals("au") || strVowel.equals("om");
}
protected static boolean isConsonant(String strConsonant) {
// Log.logInfo("came in is_consonant: Checking whether string is a
// consonant");
return strConsonant.equals("k") || strConsonant.equals("kh") || strConsonant.equals("g")
|| strConsonant.equals("gh") || strConsonant.equals("ng") || strConsonant.equals("ch") || strConsonant.equals("chh") || strConsonant.equals("j")
|| strConsonant.equals("jh") || strConsonant.equals("ny") || strConsonant.equals("t") || strConsonant.equals("th") ||
strConsonant.equals("d") || strConsonant.equals("dh") || strConsonant.equals("n") || strConsonant.equals("nn") || strConsonant.equals("p") ||
strConsonant.equals("ph") || strConsonant.equals("b") || strConsonant.equals("bh") || strConsonant.equals("m") || strConsonant.equals("y") ||
strConsonant.equals("r") || strConsonant.equals("rr") || strConsonant.equals("l") || strConsonant.equals("ll") || strConsonant.equals("lll") ||
strConsonant.equals("v") || strConsonant.equals("sh") || strConsonant.equals("ss") || strConsonant.equals("s") || strConsonant.equals("h") ||
strConsonant.equals("3") || strConsonant.equals("z") || strConsonant.equals("v") || strConsonant.equals("Ω") ||
strConsonant.equals("κ") || strConsonant.equals("K") || strConsonant.equals("γ") || strConsonant.equals("ζ") || strConsonant.equals("φ") ||
strConsonant.equals("δ") || strConsonant.equals("Δ") || strConsonant.equals("τ") || strConsonant.equals("θ") || strConsonant.equals("σ");
}
}
Outputs :-
for Short voice input :-
for Long voice Input, it stuck and can't get the result:-

The Problem is in Google's Implementation. I was facing the same type of difficulty and tried all the things, but did not work on anything.
So, i went on another way to solve this problem and the solution is implementing listeners by yourself. Here is my code for the same, it never popup the Inbuilt dialog (You can implement your custom dialog), but it works like charm.
Here is how you can do it :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original
TextView Original;
// SpeechRecognizer Object...
private SpeechRecognizer speechRecognizer;
// For TAG
private String TAG = getClass().getName();
// RecognizerIntent
private Intent recognizerIntent;
// Request Code for Permission
private static final int REQUEST_CODE_RECORD_AUDIO = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, R.string.record);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
}
// For 30 Sec it will Record...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Hindi Speech Recognition Model...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
// Permission Dialog
Askpermission();
RecordBtn.setOnClickListener(this);
}
private void Askpermission() {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_CODE_RECORD_AUDIO);
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_RECORD_AUDIO: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Operation();
} else {
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Log.d(TAG, "onClick: ");
if (checkPermission()) {
if (IsAvailable(this)) {
Log.d(TAG, "Speech Recognition Service Available...");
speechRecognizer.startListening(recognizerIntent);
} else {
Toast.makeText(this, "Speech Recognition Service not Available on your device...",
Toast.LENGTH_SHORT)
.show();
}
} else {
Askpermission();
}
break;
}
}
// Check if Speech recognition Service is Available on the Smartphone...
private boolean IsAvailable(Context context) {
return SpeechRecognizer.isRecognitionAvailable(context);
}
#Override
protected void onDestroy() {
super.onDestroy();
speechRecognizer.destroy();
}
// Check Audio Permission
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED;
}
// Start Operation
private void Operation() {
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "Audio Service is connected to Servers....");
Log.d(TAG, "You can now start your speech...");
}
#Override
public void onBeginningOfSpeech() {
Log.d(TAG, "User has started speech...");
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
Log.d(TAG, "User has Finished... speech...");
}
#Override
public void onError(int error) {
Log.d(TAG, "onError: " + error);
switch (error){
case SpeechRecognizer.ERROR_AUDIO:
Toast.makeText(MainActivity.this, "Error Recording Audio...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_CLIENT:
Toast.makeText(MainActivity.this, "Client Side Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
Toast.makeText(MainActivity.this, "Insufficient permissions...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK:
Toast.makeText(MainActivity.this, "Network Related Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NO_MATCH:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
Toast.makeText(MainActivity.this, "Recognition Busy...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SERVER:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
Toast.makeText(MainActivity.this, "Speech Timeout...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
Toast.makeText(MainActivity.this, "Network Timeout Error...", Toast
.LENGTH_SHORT).show();
}
}
#Override
public void onResults(Bundle results) {
ArrayList<String> Results = results.getStringArrayList(SpeechRecognizer
.RESULTS_RECOGNITION);
if (Results != null) {
Original.setText(Results.get(0));
}
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}

Related

PocketSphinx on Android recognises words even if they aren't spoken

I am using PocketSphinx for android-23.
I want to code an offline assistant for one of my apps.
I have successfully used recognizer.addKeyphraseSearch to initialize the assistant. For eg. In this case I say "Hello" to initialize it.
this is my entire code
public class Farmax_2 extends Activity implements
RecognitionListener {
/* Named searches allow to quickly reconfigure the decoder */
private static final String KWS_SEARCH = "wakeup";
private static final String ahead = "about";
private static final String PHONE_SEARCH = "ahead";
private static final String MENU_SEARCH = "menu";
TextToSpeech t1;
Button btn;
/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "hello";
/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_farmax_2);
// Check if user has given permission to record audio
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
return;
}
btn=(Button)findViewById(R.id.buttonme);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent inte = new Intent(Farmax_2.this, MainMenu.class);
startActivity(inte);
}
});
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});
runRecognizerSetup();
}
public void omku(View view) { Intent in=new Intent(this,abtus.class);
startActivity(in);}
private void runRecognizerSetup() {
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(Farmax_2.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
runRecognizerSetup();
} else {
finish();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (recognizer != null) {
recognizer.cancel();
recognizer.shutdown();
}
}
/**
* In partial result we get quick updates about current hypothesis. In
* keyword spotting mode we can react here, in other modes we need to wait
* for final result in onResult.
*/
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
switch (text) {
case KEYPHRASE: {
omkar();
break;
}
case ahead: {
Intent in = new Intent(this, abtus.class);
startActivity(in);
break;
// t1.speak("taking you to privacy policy of farmax.", TextToSpeech.QUEUE_FLUSH, null);
}
case PHONE_SEARCH: {
Intent in = new Intent(this, MainMenu.class);
startActivity(in);
// t1.speak("Main Menu.", TextToSpeech.QUEUE_FLUSH, null);
break;
}
}
}
private void omkar() {
t1.speak("Yes sir.", TextToSpeech.QUEUE_FLUSH, null);
switchSearch(MENU_SEARCH);
}
/**
* This callback is called when we stop the recognizer.
*/
#Override
public void onResult(Hypothesis hypothesis) {
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
/**
* We stop recognizer here to get a final result
*/
#Override
public void onEndOfSpeech() {
}
private void switchSearch(String searchName) {
recognizer.stop();
// If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
if (searchName.equals(KWS_SEARCH))
recognizer.startListening(searchName);
else
recognizer.startListening(searchName, 10000);
}
private void setupRecognizer(File assetsDir) throws IOException {
// The recognizer can be configured to perform multiple searches
// of different kind and switch between them
recognizer = SpeechRecognizerSetup.defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
.setRawLogDir(assetsDir) // To disable logging of raw audio comment out this call (takes a lot of space on the device)
.getRecognizer();
recognizer.addListener(this);
/** In your application you might not need to add all those searches.
* They are added here for demonstration. You can leave just one.
*/
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, "hello");
// Create grammar-based search for selection between demos
File menuGrammar = new File(assetsDir, "firstscn.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
// Create grammar-based search for digit recognition
}
#Override
public void onError(Exception error) {
}
#Override
public void onTimeout() {
switchSearch(KWS_SEARCH);
}
}
when I say hello, it responds correctly by replying "Yes sir" via tts. But after that it is supposed to switch menu and wait for the further commands. In this case there are two.
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
switch (text) {
case KEYPHRASE: {
omkar();
break;
}
case ahead: {
Intent in = new Intent(this, abtus.class);
startActivity(in);
break;
// t1.speak("taking you to privacy policy of farmax.", TextToSpeech.QUEUE_FLUSH, null);
}
case PHONE_SEARCH: {
Intent in = new Intent(this, MainMenu.class);
startActivity(in);
// t1.speak("Main Menu.", TextToSpeech.QUEUE_FLUSH, null);
break;
}
}
}
But the problem is that It doesnt wait for my command after it switches the menu.
Sometimes a toast pops up with "about" or sometimes with "ahead" even though I dont speak them. The app freezes badly after that and leaves me no other option than to close it.
If have also tried if else statements other than switch and case. But they don't seem to help much.
I have also tried to use the above code in onResult rather than onPartialResult but that doesnt help as well.
using sphinx tools I have created my own dictionary and grammar file.
Here is the grammar file content for this case.
#JSGF V1.0;
grammar firstscn;
public <item> = about | ahead;
Where am I going wrong? Please help me.

Google Play Services chrash when using Android Nearby Connections

I try to implement a small test application for Googles Nearby Connections API. Unfortunately on 2 of 3 tested devices Google Play Services chrash when discovering or advertising. (OnePlus One, Android 6.1; Acer Iconia, Android 4.4)
I see other devices, but when i connect to one of them play service crash (only my Honor 8 keeps on working). It says the connection is suspendend with error code 1. According to Google this means "A suspension cause informing that the service has been killed."
Maybe some of you could help. I made this code based on this tutorial.
Code without imports:
MainActivity.java
package com.example.steffen.nearbyconnectionsdemo;
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener,
Connections.ConnectionRequestListener,
Connections.MessageListener,
Connections.EndpointDiscoveryListener {
// Identify if the device is the host
private boolean mIsHost = false;
GoogleApiClient mGoogleApiClient = null;
Button bt_ad, bt_search, bt_send;
TextView tv_status;
CheckBox checkBox;
Context c;
String globalRemoteEndpointId = "";
EditText editText;
final int MY_PERMISSIONS_REQUEST = 666;
private static int[] NETWORK_TYPES = {ConnectivityManager.TYPE_WIFI,
ConnectivityManager.TYPE_ETHERNET};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
c = this;
checkPermisson();
editText = (EditText) findViewById(R.id.editText);
bt_ad = (Button) findViewById(R.id.bt_ad);
bt_ad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bt_search.setEnabled(false);
startAdvertising();
}
});
bt_search = (Button) findViewById(R.id.bt_search);
bt_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startDiscovery();
}
});
bt_send = (Button) findViewById(R.id.bt_send);
bt_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = "message: " + editText.getText().toString();
Toast.makeText(c, "Sending: " + message, Toast.LENGTH_SHORT).show();
byte[] payload = message.getBytes();
Nearby.Connections.sendReliableMessage(mGoogleApiClient, globalRemoteEndpointId, payload);
}
});
tv_status = (TextView) findViewById(R.id.tv_status);
checkBox = (CheckBox) findViewById(R.id.checkBox);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Nearby.CONNECTIONS_API)
.build();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
private boolean isConnectedToNetwork() {
ConnectivityManager connManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
for (int networkType : NETWORK_TYPES) {
NetworkInfo info = connManager.getNetworkInfo(networkType);
if (info != null && info.isConnectedOrConnecting()) {
return true;
}
}
return false;
}
private void startAdvertising() {
if (!isConnectedToNetwork()) {
// Implement logic when device is not connected to a network
tv_status.setText("No Network");
return;
}
// Identify that this device is the host
mIsHost = true;
checkBox.setChecked(mIsHost);
// Advertising with an AppIdentifer lets other devices on the
// network discover this application and prompt the user to
// install the application.
List<AppIdentifier> appIdentifierList = new ArrayList<>();
appIdentifierList.add(new AppIdentifier(getPackageName()));
AppMetadata appMetadata = new AppMetadata(appIdentifierList);
// The advertising timeout is set to run indefinitely
// Positive values represent timeout in milliseconds
long NO_TIMEOUT = 0L;
String name = null;
Nearby.Connections.startAdvertising(mGoogleApiClient, name, appMetadata, NO_TIMEOUT,
this).setResultCallback(new ResultCallback<Connections.StartAdvertisingResult>() {
#Override
public void onResult(Connections.StartAdvertisingResult result) {
if (result.getStatus().isSuccess()) {
// Device is advertising
tv_status.setText("Advertising");
} else {
int statusCode = result.getStatus().getStatusCode();
// Advertising failed - see statusCode for more details
tv_status.setText("Error: " + statusCode);
}
}
});
}
private void startDiscovery() {
if (!isConnectedToNetwork()) {
// Implement logic when device is not connected to a network
tv_status.setText("No Network");
return;
}
String serviceId = getString(R.string.service_id);
// Set an appropriate timeout length in milliseconds
long DISCOVER_TIMEOUT = 1000L;
// Discover nearby apps that are advertising with the required service ID.
Nearby.Connections.startDiscovery(mGoogleApiClient, serviceId, DISCOVER_TIMEOUT, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
// Device is discovering
tv_status.setText("Discovering");
} else {
int statusCode = status.getStatusCode();
// Advertising failed - see statusCode for more details
tv_status.setText("Error: " + statusCode);
}
}
});
}
#Override
public void onEndpointFound(final String endpointId, String deviceId,
String serviceId, final String endpointName) {
// This device is discovering endpoints and has located an advertiser.
// Write your logic to initiate a connection with the device at
// the endpoint ID
Toast.makeText(this, "Found Device: " + serviceId + ", " + endpointName + ". Start Connection Try", Toast.LENGTH_SHORT).show();
connectTo(endpointId, endpointName);
}
private void connectTo(String remoteEndpointId, final String endpointName) {
// Send a connection request to a remote endpoint. By passing 'null' for
// the name, the Nearby Connections API will construct a default name
// based on device model such as 'LGE Nexus 5'.
tv_status.setText("Connecting");
String myName = null;
byte[] myPayload = null;
Nearby.Connections.sendConnectionRequest(mGoogleApiClient, myName,
remoteEndpointId, myPayload, new Connections.ConnectionResponseCallback() {
#Override
public void onConnectionResponse(String remoteEndpointId, Status status,
byte[] bytes) {
if (status.isSuccess()) {
// Successful connection
tv_status.setText("Connected to " + endpointName);
globalRemoteEndpointId = remoteEndpointId;
} else {
// Failed connection
tv_status.setText("Connecting failed");
}
}
}, this);
}
#Override
public void onConnectionRequest(final String remoteEndpointId, String remoteDeviceId,
final String remoteEndpointName, byte[] payload) {
if (mIsHost) {
byte[] myPayload = null;
// Automatically accept all requests
Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId,
myPayload, this).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
String statusS = "Connected to " + remoteEndpointName;
Toast.makeText(c, statusS,
Toast.LENGTH_SHORT).show();
tv_status.setText(statusS);
globalRemoteEndpointId = remoteEndpointId;
} else {
String statusS = "Failed to connect to: " + remoteEndpointName;
Toast.makeText(c, statusS,
Toast.LENGTH_SHORT).show();
tv_status.setText(statusS);
}
}
});
} else {
// Clients should not be advertising and will reject all connection requests.
Nearby.Connections.rejectConnectionRequest(mGoogleApiClient, remoteEndpointId);
}
}
#Override
public void onMessageReceived(String endpointId, byte[] payload, boolean b) {
String message = payload.toString();
Toast.makeText(this, "Received from " + endpointId + ": " + message, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
tv_status.setText("Connection suspended because of " + i);
mGoogleApiClient.reconnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
tv_status.setText("Connection Failed");
}
#Override
public void onEndpointLost(String s) {
tv_status.setText("Endpoint lost: " + s);
}
#Override
public void onDisconnected(String s) {
tv_status.setText("Disconnected: " + s);
}
public void checkPermisson(){
Toast.makeText(c, "Check permission", Toast.LENGTH_SHORT).show();
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE}, MY_PERMISSIONS_REQUEST);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Toast.makeText(c, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(c, "Permission not granted, app may fail", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}

How to display a single value in android Threads

In android , i create a application based on RFID Card Reader on mobile. While i tapping Card on RFID Reader it generates same value at many times until the card untapped from the reader.
I want to show only one value per tapping card on RFID reader. Here i place my code and Sample snapshot of my application.
Guide me and tell solution for my problem.
public static MediaPlayer mp;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
Button readEnButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
long wait_sec=3000;
byte[] readData; //similar to data.
public static final int readLength = 1024; // changed length from 512
public int iavailable = 0;
char[] readDataToText;
//char readDataToTextSudha;
public boolean bReadThreadGoing = false;
public readThread read_thread;
public static D2xxManager ftD2xx = null;
boolean uart_configured = false;
// Empty Constructor
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readData = new byte[readLength];
readDataToText = new char[readLength];
//readDataToTextSudha = new char;
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
readEnButton = (Button) findViewById(R.id.readEnButton);
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
try {
ftD2xx = D2xxManager.getInstance(this);
} catch (D2xxManager.D2xxException ex) {
ex.printStackTrace();
}
//Opening Coding
if (DevCount <= 0) {
createDeviceList();
} else {
connectFunction();
}
//Configuration coding
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else {
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
readEnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else if (uart_configured == false) {
Toast.makeText(getApplicationContext(), "UART not configure yet...", Toast.LENGTH_SHORT).show();
return;
} else {
EnableRead();
}
}
});
}
public void EnableRead() {
iEnableReadFlag = (iEnableReadFlag + 1) % 2;
if (iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
Toast.makeText(getApplicationContext(),"Read Enabled",Toast.LENGTH_LONG).show();
} else {
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
Toast.makeText(getApplicationContext(),"Read Disabled",Toast.LENGTH_LONG).show();
}
}
public void createDeviceList() {
int tempDevCount = ftD2xx.createDeviceInfoList(getApplicationContext());
if (tempDevCount > 0) {
if (DevCount != tempDevCount) {
DevCount = tempDevCount;
updatePortNumberSelector();
}
} else {
DevCount = -1;
currentIndex = -1;
}
};
public void disconnectFunction() {
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ftDev != null) {
synchronized (ftDev) {
if (true == ftDev.isOpen()) {
ftDev.close();
}
}
}
}
public void connectFunction() {
int tmpProtNumber = openIndex + 1;
if (currentIndex != openIndex) {
if (null == ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
}
}
uart_configured = false;
} else {
Toast.makeText(getApplicationContext(), "Device port " + tmpProtNumber + " is already opened", Toast.LENGTH_LONG).show();
return;
}
if (ftDev == null) {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen()) {
currentIndex = openIndex;
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if (false == bReadThreadGoing) {
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
} else {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
}
}
public void updatePortNumberSelector() {
if (DevCount == 2) {
Toast.makeText(getApplicationContext(), "2 port device attached", Toast.LENGTH_SHORT).show();
} else if (DevCount == 4) {
Toast.makeText(getApplicationContext(), "4 port device attached", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "1 port device attached", Toast.LENGTH_SHORT).show();
}
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl) {
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
uart_configured = true;
Toast.makeText(getApplicationContext(), "Config done", Toast.LENGTH_SHORT).show();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (iavailable > 0) {
mp = MediaPlayer.create(MainActivity.this, R.raw.beep);
mp.start();
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread {
Handler mHandler;
readThread(Handler h) {
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run() {
int i;
while (true == bReadThreadGoing) {
try {
Thread.sleep(1000); //changed
} catch (InterruptedException e) {
}
synchronized (ftDev) {
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if (iavailable > readLength) {
iavailable = readLength;
}
ftDev.read(readData, iavailable,wait_sec);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if (DevCount > 0) {
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
My problem would snapped here
Getting Value continuously from Reader
I want this type of value when i tap the card
If i tap some other cards, old card value replaces from the new one.
Guide me.
Thanks in Advance
I got the answer by using of Threads. When the card tapping it get some values after sleep of one or two seconds only the next value have to get from the reader.
public void run() {
int i;
while (true == bReadThreadGoing) { // Means Make sure , getting value from Reader
try {
Thread.sleep(1000); // Wait for a second to get another value.
clearText(); //clear the old value and get new value.
} catch (InterruptedException e) {
}
And clearing the edittext by using this command.
public void clearText() {
runOnUiThread(new Runnable() {
public void run() {
readText.setText("");
}
});
}

Handling the case when you have missed a turn in Google Maps

I am working on an Android navigation application for blind people. So naturally no use of displaying map on the screen. My code for now gets the path by building an url and then parsing the html document. I want to make this live i.e. i want to handle the case when he/she goes off the path or goes in the wrong direction, i want my app to alert him.
Is such a thing possible using a Google Maps feature? If possible please give details about that feature or if no such feature exists then is it possible to use existing feature and use it in some way to help solve the problem.
This is my present code:
public class GPSTracking extends Activity implements
TextToSpeech.OnInitListener
{
protected static final int RESULT_SPEECH_start = 1;
protected static final int RESULT_SPEECH_end = 2;
protected static final int RESTART_ALL = 3;
//total distance travelled till last turn
Float totalDistance;
//distance to be travelled from present point to the next point
Float obtainedDistance;
//upper button
Button btnShowLocation;
//bottom button
Button btnShowLocationNo;
//to narate what user should do.
TextToSpeech tts;
//used to get name of current location
Geocoder geocoder;
//used to find positioning feature
GPS gps;
//start and position of the journey
String startPosition=null, endPosition=null;
//strings containing the path.
String[] string = null;
//vibrate the mobile
Vibrator viberator;
//indexing the present value of string which contains the path
int i = 0;
//to maintain proper order of events
int steps=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button on top
btnShowLocation = (Button) findViewById(R.id.trueButton);
//button on the lower side
btnShowLocationNo = (Button) findViewById(R.id.falseButton);
//initialising the text to speech
tts = new TextToSpeech(this, this);
//initialising the vibrator.
viberator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//to know what the current location
btnShowLocation.setOnClickListener(new View.OnClickListener() {
//to avoid start of multiple threads
boolean mytaskStarted=false;
String str=null;
#Override
public void onClick(View v) {
if(steps==0){
//to make sure values are reset
totalDistance=(float)0;
obtainedDistance=(float)0;
mytaskStarted=false;
string=null;
str=null;
i=0;
//only ask for initial position if not set
if(startPosition == null){
speakOut("Please enter the start position");
//takes the input using speech to text
intentGenerator(RESULT_SPEECH_start);
}
else{
//to enter the destination
speakOut("press the button again");
steps=1;
}
}
else if(steps==1){
//to enter the destination
speakOut("Please enter the destination");
intentGenerator(RESULT_SPEECH_end);
}
else if(steps==2){
//for a impatient user
speakOut("please wait");
//to avoid start of many asynchronous task
if(!mytaskStarted){
mytaskStarted=true;
//asynchronous task to find the path to be followed
new GetPath().execute();
}
}
else if(steps==3){
if (string != null && i < string.length) {
if(gps!=null && gps.isGpsEnabled()){
speakOut(i + 1 + " " + string[i]);
if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" m ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" m ")+3);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" km ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" km ")+4);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
obtainedDistance*=1000;
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i==0 ){
i++;
}
}
else if(gps!=null){
gps.resetDistance();
gps.stopUsingGPS();
//if gps not working.
speakOut(i + 1 + " " + string[i]);
i++;
}
else{
speakOut(i + 1 + " " + string[i]);
i++;
}
} else if (string != null && i >= string.length) {
i = 0;
}
}
}
});
//to get present location
btnShowLocation.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if(gps==null){
gps = new GPS(AndroidGPSTrackingActivity.this);
}
if (gps.canGetLocation()) {
double longitude = gps.getLongitude();
double latitude = gps.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
//obtain the address of present location
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
if (listAddresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < listAddresses.size(); i++){
Address address = listAddresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
if(address.getAddressLine(x)!=null){
result.append(address.getAddressLine(x));
result.append(",");
}
}
if(address.getLocality()!=null){
result.append(address.getLocality());
result.append("\n\n");
}
}
//if position accurate
if(gps.isGpsEnabled()){
speakOut(result.toString()+" is Your current location");
startPosition=result.toString();
Toast.makeText(
getApplicationContext(),startPosition,
Toast.LENGTH_LONG).show();
} else if(gps.isNetworkEnabled()){
speakOut(result.toString()+" is Your current approximate location. You have to give input of your present location on your own.");
Toast.makeText(
getApplicationContext(),result.toString(),
Toast.LENGTH_LONG).show();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
startPosition=null;
speakOut(" please turn on gps");
}
return false;
}
});
//to know what the previous direction string
btnShowLocationNo.setOnClickListener(new View.OnClickListener() {
int j=0;
#Override
public void onClick(View arg0) {
if(string!=null && j<string.length){
speakOut(j + 1 + " " + string[j]);
j++;
}
else if(string!=null && j>=string.length){
j=0;
}
}
});
//to reset all values for fresh start
btnShowLocationNo.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
speakOut("Values reset");
steps=0;
string=null;
i=0;
startPosition=null;
gps.stopUsingGPS();
gps=null;
endPosition=null;
return false;
}
});
}
//function to handle he text obtained from speech to text.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//set the start
case RESULT_SPEECH_start:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
startPosition = text.get(0);
steps=1;
//speakOut("please press button again");
}
else{
steps=0;
}
break;
//to set the end
case RESULT_SPEECH_end:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
endPosition = text.get(0);
steps=2;
}
else{
steps=1;
}
break;
}
}
//function to generate intent to take speech input
public void intentGenerator(int code) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, code);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
speakOut("Opps! Your device doesn't support Speech to Text");
}
}
//mobile gives instruction.
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
while (tts.isSpeaking()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//asynchronous task to get the path. THIS IS USED TO AVOID OVERLOAD THE MAIN THRED AND AVOID FORCE CLOSE OF THE APPLICATION
private class GetPath extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
string=null;
String html="";
//forming url
URL net = new URL(("http://maps.google.com/maps?saddr="+startPosition+" &daddr= "+endPosition).replaceAll(" ","%20"));
URLConnection netConnection = null;
netConnection = net.openConnection();
//to take the input from google maps
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(netConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
html+=inputLine;
}
//jsoup parser to parse the document obtained from google maps
Document doc = Jsoup.parse(html);
//obtain necessary part of the document
Elements el = doc.getElementsByClass("dir-mrgnr");
//to remove html tags
String str = el.text();
str = str.replaceAll("[0-9]+[.] ", "\n");
string = str.split("\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//so that on press of button again mobile can read the directions to users
steps=3;
}
}
#Override
public void onDestroy() {
//shutdown
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
protected void onStart() {
gps = new GPS(AndroidGPSTrackingActivity.this);
super.onStart();
}
#Override
protected void onStop() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
if(gps!=null){
gps.stopUsingGPS();
}
super.onStop();
}
#Override
public void onInit(int status) {
//initialising the text to speech
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
btnShowLocation.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
}

Android: TextToSpeech doesn't work on Android 4.1

Does anybody have idea why the TextToSpeech method I have here doesn't work anymore on Android 4.1?
On the sayIt() method it always returns Log.i(TAG, "Failure: TextToSpeech instance tts was not properly initialized");
public class SpeakSuperActivity extends Activity implements OnInitListener {
private final static String TAG = "TextToSpeech";
protected static final Locale defaultLocale = Locale.GERMAN;
private static int TTS_DATA_CHECK = 100;
protected TextToSpeech tts = null;
protected boolean ttsIsInit = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Use an Intent and startActivityForResult to check whether TTS data installed on the
// device. Result returned and acted on in method onActivityResult(int, int, Intent) below.
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, TTS_DATA_CHECK);
}
// protected void initTextToSpeech() {
// Log.d(TAG, "TTS initTextToSpeech() called");
// Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
// startActivityForResult(intent, TTS_DATA_CHECK);
// }
protected void onActivityResultOld(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK) {
Log.d(TAG, "onActivityResult: TTS_DATA_CHECK fork reached");
if (resultCode == Engine.CHECK_VOICE_DATA_PASS) {
Log.d(TAG, "Data installed: Engine.CHECK_VOICE_DATA_PASS fork reached");
tts = new TextToSpeech(this, this);
// tts = new TextToSpeech(this, new OnInitListener() {
// public void onInit(int status) {
// if (status == TextToSpeech.SUCCESS) {
// Log.w(TAG, "TTS onInit() success :)");
// ttsIsInit = true;
// if (tts.isLanguageAvailable(Locale.UK) >= 0) {
// Log.d(TAG, "Local UK available");
// tts.setLanguage(Locale.UK);
// }
// if (tts.isLanguageAvailable(Locale.GERMAN) >= 0) {
// Log.d(TAG, "Local German available");
// tts.setLanguage(Locale.GERMAN);
// }
// tts.setPitch(0.8f);
// tts.setSpeechRate(1.1f);
// speak("Hallo Sprücheklopfer");
// } else if (status == TextToSpeech.ERROR) {
// Log.w(TAG, "TTS onInit() failed :(");
// }
// }
// });
} else {
Log.i(TAG, "TTS not installed yet, calling intent to install...");
Intent installVoice = new Intent(Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installVoice);
}
}
}
// Create the TTS instance if TextToSpeech language data are installed on device. If not
// installed, attempt to install it on the device.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// Success, so create the TTS instance. But can't use it to speak until
// the onInit(status) callback defined below runs, indicating initialization.
Log.i(TAG, "Success, let's talk");
// XXX: NOTE: it is REALLY important to use new TextToSpeech(getApplicationContext(), this) instead of new TextToSpeech(this, this)!
tts = new TextToSpeech(getApplicationContext(), this);
// // Use static Locales method to list available locales on device
// Locale locales [] = Locale.getAvailableLocales();
// Log.i(TAG,"Locales Available on Device:");
// for(int i=0; i<locales.length; i++){
// String temp = "Locale "+i+": "+locales[i]+" Language="
// +locales[i].getDisplayLanguage();
// if(locales[i].getDisplayCountry() != "") {
// temp += " Country="+locales[i].getDisplayCountry();
// }
// Log.i(TAG, temp);
// }
} else {
// missing data, so install it on the device
Log.i(TAG, "Missing Data; Install it");
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
ttsIsInit = true;
// Set to a language locale after checking availability
Log.i(TAG, "defaultLocaleAvailable=" + tts.isLanguageAvailable(defaultLocale));
tts.setLanguage(defaultLocale);
// Examples of voice controls. Set to defaults of 1.0.
tts.setPitch(1.0F);
tts.setSpeechRate(1.0F);
// Issue a greeting and instructions in the default language
// speakGreeting(defaultLocale.getDisplayLanguage());
// sayIt("Hallo Sprücheklopfer", true);
} else {
ttsIsInit = false;
Log.i(TAG, "Failure: TextToSpeech instance tts was not properly initialized");
}
}
// protected void speak(String text) {
// Log.d(TAG, "TTS sould say: " + text);
// if (tts != null && ttsIsInit) {
// tts.speak(text, TextToSpeech.QUEUE_ADD, null);
// } else {
// Log.w(TAG, "TTS not initialised or null");
// }
// }
// Method to speak a string. The boolean flushQ determines whether the text is
// appended to the queue (if false), or if the queue is flushed first (if true).
public void sayIt(String text, boolean flushQ) {
if (tts != null && ttsIsInit) {
if (flushQ) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
} else {
Log.i(TAG, "Failure: TextToSpeech instance tts was not properly initialized");
}
}
// Release TTS resources when finished
#Override
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
ttsIsInit = false;
}
super.onDestroy();
}
public void onInitOld(int status) {
Log.i(TAG, "TTS onInit() status :" + status);
if (status == TextToSpeech.SUCCESS) {
Log.w(TAG, "TTS onInit() success :)");
ttsIsInit = true;
if (tts.isLanguageAvailable(Locale.UK) >= 0) {
Log.d(TAG, "Local UK available");
tts.setLanguage(Locale.UK);
}
if (tts.isLanguageAvailable(Locale.GERMAN) >= 0) {
Log.d(TAG, "Local German available");
tts.setLanguage(Locale.GERMAN);
}
tts.setPitch(0.8f);
tts.setSpeechRate(1.1f);
sayIt("Hallo Sprücheklopfer", true);
} else if (status == TextToSpeech.ERROR) {
Log.w(TAG, "TTS onInit() failed :(");
} else {
Log.w(TAG, "TTS onInit() unknown status :" + status);
}
}
}

Categories

Resources