There are many tutorials online for adding voice recognition to an android app. They are often confusing and the publishers of the coding are never available for questions. I need a basic overview of how to add voice recognition to my app (as an answer, not a link).
If you want to add voice recognition to your group's Android app it is very simple.
Throughout this tutorial you will need to add imports as you paste in the code.
Create an xml file or use an existing one and make sure that you add a button and a listview.
In a java class you need to extend activity and implement OnClickListener
You will get an error that says you have unimplemented methods. Hover over it and add the unimplemented methods. We will add to this later.
Next set up the button and listview in your java.
public ListView mList;
public Button speakButton;
also add:
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
Next, make an OnCreate Method and set up the button and listener.
speakButton = (Button) findViewById(R.id.btn_speak);
speakButton.setOnClickListener(this);
also add this method(we will set it up next)
voiceinputbuttons();
Remember to setContentView for the xml you are showing.
Outside of your oncreate make a new method that looks like this.
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
Now you will have to set up your voice recognition activity by using the following code.
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
Next, inside your onclick method from step 2 add the activity from step 6.
startVoiceRecognitionActivity();
Next we will have to set up another method. Copy and paste the following code.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches));
matches is the result of voice input. It is a list of what the user possibly said. Using an if statement for the keyword you want to use allows the use of any activity if keywords match it is possible to set up multiple keywords to use the same activity so more than one word will allow the user To use the activity (makes it so the user doesn't have to memorize words from a list) To use an activity from the voice input information simply use the following format;
if (matches.contains("information")) {
informationMenu();
}
NOTE: you can format the code any time by pressing ctrl+shift+F in eclipse.
Now we are going to set up our method used by the code in step 8. This code creates an intent to direct the user to a new menu. You will need another xml and java class for this. Also, remember to add an activity to your manifest.
public void informationMenu() {
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
Finally you need to set up some code that will let the user know if the mic is operational. Paste this code inside of the OnCreate method at the end.
// Check to see if a recognition activity is present
// if running on AVD virtual device it will give this message. The mic
// required only works on an actual android device
PackageManager pm = getPackageManager();
List activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
voiceButton.setOnClickListener(this);
} else {
voiceButton.setEnabled(false);
voiceButton.setText("Recognizer not present");
}
FINAL NOTE: Voice Recognition will not work on a virtual emulator because they can't access the mic on your computer. The voice recognition will only work with an internet connection.
This is approx. what your final code should look like in your java.
package com.example.com.tutorialthread;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.speech.RecognizerIntent;
import android.support.v4.app.NavUtils;
public class main extends Activity implements OnClickListener {
public ListView mList;
public Button speakButton;
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
speakButton = (Button) findViewById(R.id.btn_speak);
speakButton.setOnClickListener(this);
voiceinputbuttons();
}
public void informationMenu() {
startActivity(new Intent("android.intent.action.INFOSCREEN"));
}
public void voiceinputbuttons() {
speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
}
public void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
public void onClick(View v) {
// TODO Auto-generated method stub
startVoiceRecognitionActivity();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, matches));
// matches is the result of voice input. It is a list of what the
// user possibly said.
// Using an if statement for the keyword you want to use allows the
// use of any activity if keywords match
// it is possible to set up multiple keywords to use the same
// activity so more than one word will allow the user
// to use the activity (makes it so the user doesn't have to
// memorize words from a list)
// to use an activity from the voice input information simply use
// the following format;
// if (matches.contains("keyword here") { startActivity(new
// Intent("name.of.manifest.ACTIVITY")
if (matches.contains("information")) {
informationMenu();
}
}
}
Really good tutorial. Well done.
To complete a little bit more :
You need to add permission to your manifest as follow
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Also voice does not work if you have
launchMode="singleInstance" or launchMode="singleTask" it looks like it should be "standard"
Related
This is the code for an Activity named as Interest Activity. It is a dashboard which consist of four interest/hobbies (gaming, singing, sports, and coding). The user is asked to choose one of the them and then he/she is redirected to the particular activity. I used Cardview to represent the interest they behave like a button. This is the code:
package com.example.meetup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class InterestActivity extends AppCompatActivity {
CardView cardGame;
CardView cardSports;
CardView cardSing;
CardView cardCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interest);
cardGame = findViewById(R.id.cardGame);
cardCode = findViewById(R.id.cardCode);
cardSing = findViewById(R.id.cardSing);
cardSports = findViewById(R.id.cardSports);
cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Gaming", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
cardSports.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Sports", Toast.LENGTH_SHORT).show();
}
});
cardSing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Singing", Toast.LENGTH_SHORT).show();
}
});
cardCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Coding", Toast.LENGTH_SHORT).show();
}
});
}
}
Now the problem is that whenever I am reopening the app, it takes me to the interest activity again even though I chose an interest once. Then I got to know about shared preference as how it stores the user data and intent accordingly.
I saw many tutorials on YouTube as to how could I use it, but they all were taking something as input like text. But in my case I’m not taking any input just pushing a button. How do I use a shared preference in my case? Can you give a shared preference code for if the user chooses gaming?
Define some constants to manage saved selected interest
public class InterestActivity extends AppCompatActivity {
// Define a string key for SharedPreference value
private static final String SP_INTEREST = "interest"
// Define integer codes for each interest
private static final int INTEREST_NONE = 0
private static final int INTEREST_GAME = 1
private static final int INTEREST_SPORTS = 2
private static final int INTEREST_SING = 3
private static final int INTEREST_CODE = 4
SharedPreferences sp;
SharedPreferences.Editor editor;
CardView cardGame;
CardView cardSports;
CardView cardSing;
CardView cardCode;
// Rest of the code
}
Then for saving the choosen interest, repeat it for each on click:
cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Gaming", Toast.LENGTH_SHORT).show();
// Here first save the choosen interest
editor.putInt(SP_INTEREST, INTEREST_GAME);
editor.apply();
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
And when you restart the app, in on create method check the saved interest code and start the corresponding activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get and init SharedPreferences and editor
SharedPreferences sp = getSharedPreferences(getPackageName(), MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// INTEREST_NONE is the default value if there no registry.
int savedInterest = sp.getInt(SP_INTEREST, INTEREST_NONE);
if(INTEREST_GAME == savedInterest) {
// Start game activity using intent
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else if(INTEREST_SPORTS == savedInterest) {
// Start sports activity using intent
}
else if(INTEREST_SING == savedInterest) {
// Start sing activity using intent
}
else if(INTEREST_CODE == savedInterest) {
// Start code activity using intent
}
setContentView(R.layout.activity_interest);
// Rest of the onCreate codes
}
If you want to store what the user clicked the last time and do something about it, you can follow this to write/read from shared preferences: https://stackoverflow.com/a/3624358/7365491
Every time the user clicks on one of your CardViews you store a value of the last selected interest.
Every time the user opens the app in the onCreate, check if the preference exists and read the last stored value in it. With that then you can decide what you want to do when the app is opened and the user has previously selected a value.
I have an application that uses crosswalk. I use it in two activities.
In this activity, I have a crosswalk view that shows a list of selectable items and when selected launch another activity.
In this new activity I open another crosswalk view that runs the selected item from the previous activity.
The issue that I am having is when in the second activity when I press the back button it goes back to a black screen. If I press the back button again, it then closes the activity.
What can I do to close the activity instead of going back to the black screen? This doesn't happen on all items just a few, and with those few I think that a page redirect is happening in crosswalk so when I press back it just goes to the previous screen.
Here is the activity:
package com.gamesmart.gamesmart;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.xwalk.core.XWalkPreferences;
import org.xwalk.core.XWalkView;
public class Play extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
Intent intent = getIntent();
String url = intent.getStringExtra("url");
XWalkView xWalkWebView = (XWalkView)findViewById(R.id.xwalkWebViewPlay);
// Turn on debugging if we are in DEBUG mode
if (BuildConfig.DEBUG) {
XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);
}
// Load the url
xWalkWebView.load(url, null);
}
#Override
public void onBackPressed(){
finish();
}
}
I don't think that my onBackPressed is doing what it should be...
You forgot
super.onBackPressed();
Just use below code
#Override
public void onBackPressed() {
super.onBackPressed();
}
Try this
public void onBackPressed(){
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
Maybe you should try to call the super method in your onBackPressed(), or if you want to go back to the previous activity, to bring to front the other activity in your onBackPressed(), and then, finish your Activity like this :
public void onBackPressed() {
Intent main = new Intent(this, YourClass.class);
main.putFlags(Intent.ACTIVITY_BROUGHT_TO_FRONT); // Or something like this, I dont really remember the flag name
startActivity(main);
super.onBackPressed();
}
Just write this command when you want to exit :
overridePendingTransition ( 0 , 0 );
super.finish ( );
super.onStop ( );
super.onDestroy ( );
overridePendingTransition ( 0 , 0 );
I need to randomly generate a button and then grab elements from it from the activity that the button opens. Specifically the universal ID of a "character" that I have specified in PersistentData. (That whole class works fine, though. The problem is between this activity and the next.) The child activity has multiple activities that can call it. (There are several activities with lists made from different characters from a pool, and each list has these buttons that are shown below, which all point to the same activity that loads information from PersistentData based on the data that its supposed to pull from said button.) The following 1 block of code is in the onCreate method for this activity. (Automatically generated, I just added this in after I called the layouts from the XML file)
for (fID = 0; fID < PersistentData.fName.size(); fID++) {
if (PersistentData.fName.get(fID) != null) {
Button[] Btn = new Button[PersistentData.fName.size()];
Btn[fID].setHeight(200);
Btn[fID].setWidth(200);
Btn[fID].setTextSize(40);
Btn[fID].setText(PersistentData.fName.get(fID));
Btn[fID].setTag(fID);
Layout.addView(Btn[fID]);
Btn[fID].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int btnID = fID;
gotoActivity(v);
}
});
} else continue;
}
Here is gotoActivity(). (In the class, not onCreate)
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
intent.putExtra("btnClicked", /*IDK WHAT TO PUT RIGHT HERE*/);
}
I have put several things there, actually. Mostly, they have been various ways of declaring a variable on the creation of the button.
Here's the TargetActivity.class
public class Fighter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fighter);
Intent intent = getIntent();
Bundle bundle =
intent.getExtras(); //line ***
**
TextView viewName = (TextView) findViewById(R.id.fighterName);
viewName.setText(PersistentData.fName.get(fID));
}
}
What should I put in the other class that I should get here**? (fID) is the thing that I'm trying to get. I have tried putting and getting fID using the methods as described in the Create an Activity page from Android and it continued to give me a NullPointerException at line *** (I split the line to be precise.)
Any help is appreciated. I would not be surprised if there is a better way to do this, requiring me to scrap all my work and restart. I would prefer not to, though lol. I will be checking this post periodically throughout the day, so if you have any questions or require more detail, just post or message me. Thank you beforehand.
I think the reason you got a NullPointerException because you started the activity before persing the extra.
In the gotoActiviy, make sure the extra(s) method are called before you start the activity. that is
public void gotoActivity(View view) {
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("btnClicked", "Strings");
startActivity(intent);
}
As you can see, a string was the extra, you can put any variable type as the extra just make sure at the activity being called, the same variable type gets the extra.
as an example
String getValue = getIntent().getExtras().getString("btnClicked");
Int getValue = getIntent().getExtras().getInt("btnClicked");
/** If integer was the value activity extra */
I'm currently making an app that will play some music.
There will be multiple activities, one for each song. There are usually 3 buttons per screen: One to play/pause the music, one for going to the previous page, and one for going to the next page.
Currently, Android is confused about which buttons are supposed to do what. When I click on the 'Play Music' button, the app attempts to take me to the next screen. When I click on the 'Next Page' button, it brings me to the previous page. When I click on the 'Last Page' button, it plays/pauses the song.
This is my java code for the relevant activity.
package net.jacksonhamilton.calmingmusic;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Rush extends Activity {
Button btnRush, btnRushtoCivil, btnRushtoNeil;
MediaPlayer tomsawyer;
int playing;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rush);
btnRush = (Button) findViewById(R.id.btnRush);
btnRushtoCivil = (Button) findViewById(R.id.btnRushtoCivil);
btnRushtoNeil = (Button) findViewById(R.id.btnRushtoNeil);
btnRush.setOnClickListener(btRush);
btnRushtoCivil.setOnClickListener(btRushtoCivil);
btnRushtoNeil.setOnClickListener(btRushtoNeil);
tomsawyer = new MediaPlayer();
tomsawyer = MediaPlayer.create(this, R.raw.tomsawyer);
playing = 0;
// TODO Auto-generated method stub
}
Button.OnClickListener btRush = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (playing) {
case 0:
tomsawyer.start();
playing = 1;
btnRush.setText("Pause 'Tom Sawyer', by Rush");
break;
case 1:
tomsawyer.pause();
playing = 0;
btnRush.setText("Play 'Tom Sawyer', by Rush");
break;
}
}
};
Button.OnClickListener btRushtoCivil = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tomsawyer.stop();
startActivity(new Intent(Rush.this, Splash.class));
}
};
Button.OnClickListener btRushtoNeil = new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tomsawyer.stop();
startActivity(new Intent(Rush.this, Neilyoung.class));
}
};
}
I've checked the IDs in the XML layout file, both graphically and in code. All buttons are assigned the proper IDs and the proper string value (for the text on the buttons).
I have the app set to require SDK15 as the minimum, and it is targeted to SDK19. It is also compiling with SDK19.
If it matters, I am developing the app in Eclipse Mars.
If you'd like to see the app for reference, here is a picture of the Activity.
You must have messed something up in the layout file, or you may be running some old version of the app. It sometimes happens in Eclipse that it does not rebuild the app but starts a last built version instead. Try deleting the app from the device/emulator, restarting the emulator, cleaning project or restarting IDE.
What I'm trying to do is Live Wallpaper with some action(that is already done)but the problem is there..that I've made it in Activity which "action" is an class who extends view and the Activity's setContentView() method isn't some layout ..it is this View.And what I'm trying to do now is to create option to set that activity as wallpaper,but I don't know how. This is my onCreate() method from the main Activity which is loading the View. I want that to be an Wallpaper..so how can I set it up to be one?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SnowFall snowFallView = new SnowFall(this);
setContentView(snowFallView);
snowFallView.setBackgroundDrawable(getResources().getDrawable(
R.drawable.christmas));
}
Here's example app for what I want to create: https://play.google.com/store/apps/details?id=com.chiralcode.wallpaper.autumn&hl=bg
Did you implement wallpaper as a service? Get the basics - check Lars Vogel's tutorial on live wallpapers here
In short, you can set the wallpaper with an intent:
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, MyWallpaperService.class));
startActivity(intent);
You will need to adapt the above to your class names, and remember to have the permission android.permission.BIND_WALLPAPER in your AndroidManifest, but again, read his tutorial.
Start Wallpaper service through activity , following is perfect working for that, you can put following in onclick(...) also, if you start livewallpaper ( your own live wallpaper directly through just one click) you just write following code,
btnInstallWallpaper.setOnClickListener(new OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressLint("InlinedApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
if (android.os.Build.VERSION.SDK_INT >= 16)
{
intent.setAction("android.service.wallpaper.CHANGE_LIVE_WALLPAPER");
intent.putExtra("android.service.wallpaper.extra.LIVE_WALLPAPER_COMPONENT", new ComponentName("com.example.wall", "com.example.wall.WallpaperService"));
} else
intent.setAction("android.service.wallpaper.LIVE_WALLPAPER_CHOOSER");
intent.putExtra("android.service.wallpaper.extra.LIVE_WALLPAPER_COMPONENT", new ComponentName("com.example.wall", "com.example.wall.WallpaperService")); // package + classname
//}
startActivity(intent);
}
});