How to use in-built voice recognition in my Android app? - java

I want to use offline voice recognition in my app.
Setting -> “Language and Input” -> "Google Voice Typing" -> "Offline speech recognition" :- I would like to use this built-in feature.
In the below code, I tried to implement it using Recognizer Intent, but it uses the Google voice search (works online). Please help.
public class MainActivity extends AppCompatActivity {
private TextView txtSpeechInput;
private ImageButton btnSpeak;
private final int REQ_CODE_SPEECH_INPUT = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
promptSpeechInput();
//onCreateOptionsMenu();
}
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//txtSpeechInput.setText(result.get(0));
{
String a="camera";
if(a.compareTo(result.get(0))==0){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()) != null) {
startActivityForResult(i, 1);
}
}
}
}
break;
}
}
}
Well, here I am sending intent to camera via voice. So, I have a limited vocabulary requirement here.

Try this:
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE,true);
Note: This will work only on API level 23 and above.

Related

How to check from which onResume the user is coming

I have a problem. The following Picture visualises my issue. We start in App 1 and press the button. Now we either get to see the screen of app2 or the setting screen. Now when i press the back button (marked as the red circle in app2 and settings) and we get back to the app1 screen. But what i wanna know is from what screen we get back to the app1 screen.
#Override
protected void onResume() {
super.onResume();
// if(from setting) {
// do this
}
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivity(userHomeScreen);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc_setting);
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (currentUser != null){
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivity(userHomeScreen);
}else{
Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginScreen);
}
}
else {
btn_nfc_navigate_setting = findViewById(R.id.btn_nfc_navigate_setting);
btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_NFC_SETTINGS));
}
});
}
Look now that I understand whats going on, you have to startActivityForResult() not startActivity():
Now in the activity that you use to open other activities:
When you open Log in screen:
Intent loginScreen = new Intent(getApplicationContext(), LoginActivity.class);
int requestCode = 10;
startActivityForResult(loginScreen , requestCode);
When you open settings
btn_nfc_navigate_setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int requestCode = 11;
startActivityForResult(new Intent(Settings.ACTION_NFC_SETTINGS) , requestCode);
}
});
Override this method to listen to from where you came instead of onResume()
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//this is triggered when you come back to this activity
if(requestCode == 10){
//we came from login
}else if(requestCode == 11){
//we came from settings
}
}
Use startActivityForResult()
From App1 to App2 or Setting:
int FLAG_APP2 = 1
Intent i = new Intent(this, App2.class);
startActivityForResult(i, FLAG_APP2);
Then in App2 button back tapped:
finish();
Then in App1 override onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FLAG_APP2) {
//here you know this is from App2 Screen
}
}
If you want to know the result of an Intent (in this case settings or app2), you can use
startActivityForResult(intent, requestCode)
instead of
startActivity(intent).
Where request code should be unique for different intents (in this case settings and app2).
To handle the result you have to override the onActivityResult() in the actvity.
So your required code will be
#Override
protected void onResume() {
super.onResume();
// if(from setting) {
// do this
// }
NfcManager manager = (NfcManager) this.getSystemService(Context.NFC_SERVICE);
NfcAdapter adapter = manager.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) {
Intent userHomeScreen = new Intent(getApplicationContext(), UserHomeActivity.class);
startActivityForResult(userHomeScreen,1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
// Activity returned from userHomeScreen
}
else if (requestCode ==2) {
// Activity returned from Settings
}
}
UPDATE:
To add to that above if you want to access any Settings FEATURE you can use SETTINGS Constants as intent parameters.
Settings Documentation
For example, if you want to access NFC settings:
// Look into the constants in the documentation to know which constants to use in intent
Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
startActivityForResult(intent, 2);

How to implement speech to text in my app

I am building an app that utilities speech to text, in my code everything seems fine till it gets to protected void onActivityResult method to handle the results, it generates an error saying onActivityResult is a variable and then if I delete the access modifier, it sees it as a method then it generates another error in the parameters saying identifier expected and token is missing
Any help would be greatly appreciated.
My code
private static final int SPEECH_REQUEST_CODE = 100;
// Create an intent that can start the Speech Recognizer activity
private void displaySpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// Start the activity, the intent will be populated with the speech text
startActivityForResult(intent, SPEECH_REQUEST_CODE);
}
// This callback is invoked when the Speech Recognizer returns.
// This is where you process the intent and extract the speech text from the intent.
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) {
List<String> results = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
Output.setText(results.get(0));
}
}
DO it like this:
private void displaySpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
And in onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
}
break;
}
}
}
And in onCreate:
//Button you craete to start speech recognition
Button btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
//getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displaySpeechRecognizer();
}
});

Android Java, Setting text of a field outside of the application

I'm currently writing an Android application that will allow a user to input the result of a scanned barcode into a field outside of the application.
The app will simply be a Floating Button that when pressed, will bring up a camera screen that scans and reads the barcode being pointed at, and save the result as an intent.
The user will primarily be working on Chrome when using this Floating Button.
Question: Is it possible to set the text of the current field in focus, outside of the application, as the result of the scanned barcode?
I'm using the following libraries:
- com.google.zxing:core:3.3.3
- com.journeyapps:zxing-android-embedded:3.5.0#aar
Current code:
public class MainActivity extends AppCompatActivity {
FloatingActionButton fabScan;
TextView textViewScanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity = this;
textViewScanResult = findViewById(R.id.textViewScan);
fabScan = findViewById(R.id.floatingActionButton_scan);
fabScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan Barcode");
integrator.setCameraId(0);
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(false);
integrator.setOrientationLocked(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(getApplicationContext(), "nothing", Toast.LENGTH_SHORT).show();
} else {
textViewScanResult.setText(result.getContents());
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Currently, i'm only setting a textView as the scanned result.
try setting browser intent with the result content.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(getApplicationContext(), "nothing", Toast.LENGTH_SHORT).show();
} else {
textViewScanResult.setText();
//here
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.stackoverflow.com")); //change url to google
intent.putExtra(result.getContents().toString());
startActivity(intent);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}

Zxing Scanner App, How to show a result as a yes or no?

Using zxing on Android Studio with empty activity and 4.4 KitKat. I would like to show the result as a yes or no. I would like to reference a google sheet with the UPC codes. If the UPC is in the spreadsheet already then show "YES" or if the UPC is not in the spreadsheet show "NO". Can I use an "If, Else" in the MainActivity java code using only the UPC column on the google sheet?
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
I want to show this code as a "Yes" or "NO" based on if the scanned barcode is already in the spreadsheet. My question is how to get the spreadsheet to communicate with the scanner or can copy all of the barcodes from the spreadsheet in a boolean?
Set<String> getStringSet (String key,
Set<String> defValues)
makeText(Context context, int resId, int duration)
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
So above is what ive come up with from search. Is it practical to use shared preference to store my data(1000 UPC) use ZXING to parse as well as IF ELSE to check the code and finally TOAST to show "YES" or "NO" based on if my result is located in the shared preference?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = this.findViewById(R.id.button);
final Activity activity = this;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
public void scanCode(View view) {
}
public class myWebView extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = new WebView(this);
setContentView(webview);
WebView myWebView = findViewById(R.id.myWebView);
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webview.loadUrl("https://google.com/");
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
}
for segregation of code you need to create SacnActivity as a separate activity which is extend Activity and impliments ZXingScannerView.ResultHandler and call from the MainActivity and give call back to Mainactivity in onActivityResult().
MainActivity
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan = (Button)findViewById(R.id.btnScan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(MainActivity.this,SacnActivity .class),1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
Log.d("result================>",""+result);
try {
//processData(result);
} catch (Exception e) {
e.printStackTrace();
}
}
if (resultCode == Activity.RESULT_CANCELED) {

Voice Recognition without Google Dialog

I am trying to use the Speech recognition without dialog with RecognitionListener, but it doesn't work. The following codes are the way now I use, and the bottom codes (test part) are for checking that could phone receive my commanding. Additionally, I have added permissions Audio. Finally, I don't want there have any button.
This is my first time asking question, so hope I dont violate any unspoken rules.
Thank you very much,
public class Step extends AppCompatActivity {
private final int SPEECH_RECOGNITION_CODE = 1;
private TextView txtOutput;
private Button btnMicrophone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step);
txtOutput = (TextView) findViewById(R.id.txt_output);
btnMicrophone = (Button) findViewById(R.id.btn_mic);
startSpeechToText();
btnMicrophone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSpeechToText();
}
});
}
private void startSpeechToText() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "SPEAK");
try {
startActivityForResult(intent, SPEECH_RECOGNITION_CODE);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(), "Sorry! Speech recognition is not supported in this device.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SPEECH_RECOGNITION_CODE: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String text = result.get(0);
txtOutput.setText(text);
test(txtOutput.getText().toString());
startSpeechToText();
}
break;
}
}
}
public void test (String com) {
for(int i=0;i<com.length();i++) {
if (com.startsWith("good",i)) {
com = com + "123";
Toast.makeText(CookStep.this, com, Toast.LENGTH_SHORT).show();
}
}
if(com.compareToIgnoreCase("OK")==0){
com=com+"456";
Toast.makeText(CookStep.this, com, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(CookStep.this, com, Toast.LENGTH_SHORT).show();
}
}
}

Categories