ProgressDialog shows up after thread is done - java

I have the following three classes:
When I try to show a progressDialog when the WorkingThread is running, the ProgressDialog only shows up after the WorkingThread is done. What am I doing wrong?
I am not interested in using an AsyncTask!
-StartActivity:
public class StartActivity extends Activity implements OnClickListener
{
public ProgressDialog pgd;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgv = (ImageView)findViewById(R.id.imageView1);
tv = (TextView)findViewById(R.id.textview);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
}
public void onClick(View v)
{
pgd = ProgressDialog.show(StartActivity.this, "", "Loading picture"); // Start ProgressDialog before starting activity
Intent ActivityIntent = new Intent(this, FirstActivity.class);
startActivityForResult(ActivityIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK)
{
pgd.dismiss(); //Stop ProgressDialog when FirstActivity is "done"
}
}
}
-
-FirstActivity:
public class FirstActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WorkingThread wt = new WorkingThread();
wt.start();
try
{
wt.join();
Intent ActivityIntent = getIntent();
setResult(RESULT_OK, ActivityIntent);
finish();
}
catch (Exception e)
{
}
}
}
-WorkingThread:
public class WorkingThread extends Thread
{
#Override
public void run()
{
super.run();
try
{
Thread.sleep(5000);
}
catch (Exception e)
{
}
}
}

The problem is ProgressDialog always need current Activity context for display.But in your case ProgressDialog is little unfortunate
The reason is as soon as you fire ProgressDialog the next couple of lines take out Context from Current activity and starts Next Activity i.e FirstActivity.So your progressDialog gets no chance to present itself on the Screen.

Use an AsyncTask. Here's an example:
package com.example.test;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
ProgressDialog activityProgressDialog;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new TestAsyncTask().execute();
}
});
}
private class TestAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
//Called before doInBackground.
//Initialize your progressDialog here.
activityProgressDialog = ProgressDialog.show(context,
"Test",
"Doing heavy work on background...", false,
false);
}
#Override
protected Void doInBackground(Void... v) {
//Do your work here
//Important!!! Update any UI element on preExcecute and
//onPostExcecute not in this method or else you will get an
//exception.
//The below code just make the thread inactive for 5 seconds.
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().notify();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void v) {
//Dismiss the progessDialog here.
activityProgressDialog.dismiss();
}
}
}
I just show your edit that you don't want to use an AsyncTask. I will not delete this answer (unless you want me to) since it is another way of doing what you wanted to do.

try
{
wt.join();
Intent ActivityIntent = getIntent();
setResult(RESULT_OK, ActivityIntent);
finish();
}
here is your problem. The UI thread is waiting the Working Thread to finish becaouse of the join().

Related

Splash Animation shows only once in Android

The splash screen's supposed to work every time I use my app But once I clear the application from task manager and restart it.
The animation doesn't appear and it goes straight to the login screen with no animation occurring.
package com.example.promilek;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
#SuppressLint("CustomSplashScreen")
public class SplashScreen extends AppCompatActivity {
private static final int SPLASH_SCREEN = 2000;
//Variables
Animation topAnim;
ImageView ImageViewButla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow() .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
topAnim= AnimationUtils.loadAnimation(this, R.anim.top_animation);
ImageViewButla = findViewById(R.id.imageViewButla);
ImageViewButla.setAnimation(topAnim);
new Handler() .postDelayed(() -> {
Intent intent = new Intent(SplashScreen.this, Login.class);
startActivity(intent);
finish();
},SPLASH_SCREEN);
}
}
In my solution, I will use the Thread class to do this. At least this will give you more control in the activity lifecycle methods.
I have also included a SessionManager to help you incase you need it now or later.
Activity with animation
#SuppressLint("CustomSplashScreen")
public class SplashScreen extends AppCompatActivity {
private static final int SPLASH_SCREEN = 2000;
//Variables
Animation topAnim;
ImageView ImageViewButla;
private Thread counterThread;
Context mContext;
private SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow() .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
mContext = getApplicationContext(); // Get application context
topAnim = AnimationUtils.loadAnimation(this, R.anim.top_animation);
ImageViewButla = findViewById(R.id.imageViewButla);
ImageViewButla.setAnimation(topAnim);
sessionManager = new SessionManager(mContext); // Initialize Session manager object
// Counter thread
counterThread = new Thread() {
#Override
public void run() {
try {
int wait = 0; // Thread wait time
// Loop
while (wait < SPLASH_SCREEN) {
sleep(100); // Sleep
wait += 100;
}
Intent intent;
if (sessionManager.isSignedIn()) {
// Launch MainActivity
intent = new Intent(SplashActivity.this, MainActivity.class);
} else {
// Launch Signin or SignUp activity
intent = new Intent(SplashActivity.this,
SignInSignUpActivity.class);
}
startActivity(intent); // Start activity
finish(); // Exit Activity
} catch (Exception ignored) {
} finally {
finish(); // Exit Activity
}
}
};
}
}
#Override
public void onBackPressed() {
super.onBackPressed(); // Exit
counterThread.start(); // Start thread
}
#Override
public void onResume() {
super.onResume();
counterThread.start(); // Start thread
}
#Override
protected void onStop() {
super.onStop();
counterThread.interrupt(); // Interrupt thread on activity exit
}
#Override
protected void onDestroy() {
super.onDestroy();
counterThread.interrupt(); // Interrupt thread on activity exit
}
SessionManager class
Below is the code for the session manager
public class SessionManager {
private static final String KEY_IS_SIGNED_IN = "isSignedIn";
private static String PREFERENCE_NAME; // Shared Preference File Name
// Shared Preference
private final SharedPreferences sharedPreferences;
private final SharedPreferences.Editor editor;
// Shared Preference mode
int PRIVATE_MODE = 0;
#SuppressLint("CommitPrefEdits")
public SessionManager(Context context) {
this.sharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, PRIVATE_MODE);
this.editor = sharedPreferences.edit();
PREFERENCE_NAME = context.getResources().getString(R.string.app_name) +
"_SessionManagerPreference";
}
public boolean isSignedIn() {
return sharedPreferences.getBoolean(KEY_IS_SIGNED_IN, false);
}
public void setSignedIn(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_SIGNED_IN, isLoggedIn);
editor.commit(); // Commit Changes
}
}

add data to listview from another activity

I'm really confused on how to add from another activity I keep getting an error in this part of the code:
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
So the error says "actual and formal argument lists differ in length". if anyone could help me out it would be such a huge help thank you :)
this my code:
main activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button newEmail;
private ListView listView;
private EmailAdapter emailAdapter;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
emailAdapter = new EmailAdapter(this, emailsArrayList);
listView.setAdapter(emailAdapter);
updateList();
newEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SendActivity.class);
startActivity(intent);
}
});
}
private void init(){
newEmail = (Button) findViewById(R.id.newBtn);
listView = (ListView) findViewById(R.id.list);
emailsArrayList = new ArrayList<>();
Emails emails = new Emails ();
emails.setEmails("josemari#yahey.com");
emails.setSubject("Sample Data");
emails.setBody("this is the sample data");
emailsArrayList.add(emails);
}
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onStart() {
super.onStart();
Log.d("MainActivity","onStart invoked");
}
#Override
protected void onResume() {
super.onResume();
Log.d("MainActivity","onResume invoked");
}
#Override
protected void onPause() {
super.onPause();
Log.d("MainActivity","onPause invoked");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
this is the add item activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class SendActivity extends AppCompatActivity {
private Button send;
private Button discard;
private EditText email;
private EditText subject;
private EditText body;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
send = (Button) findViewById(R.id.sendBtn);
discard = (Button) findViewById(R.id.discardBtn);
email = (EditText) findViewById(R.id.inputEmail);
subject = (EditText) findViewById(R.id.inputSubject);
body = (EditText) findViewById(R.id.inputBody);
discard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SendActivity.this, MainActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputEmail = email.getText().toString();
String inputSubject = subject.getText().toString();
String inputBody = body.getText().toString();
if (inputBody.isEmpty() || inputEmail.isEmpty() || inputEmail.isEmpty()){
Toast.makeText(SendActivity.this, "Please enter the following data", Toast.LENGTH_SHORT).show();
}
else {
emailsArrayList = new ArrayList<>();
Emails newEmails = new Emails ();
newEmails.setEmails(inputEmail);
newEmails.setSubject(inputSubject);
newEmails.setBody(inputBody);
emailsArrayList.add(newEmails);
Intent intent = new Intent();
getIntent().putExtra("inputEmail", inputEmail);
getIntent().putExtra("inputSubject", inputSubject);
getIntent().putExtra("inputBody", inputBody);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}
I would also change the following as well:
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
to
private void updateList()
{
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle != null)
{
Emails a = new Emails(String)bundle.get("inputEmail"), (String)bundle.get("inputBody"), (String)bundle.get("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
I would try this absolutley first: You may beable to use what you have and just change the Bundle bundle and Intent intent lines around in your updateList(). Again no expert but try that first and then above that second. I hope it works for you.

Losing state of the activity when navigating from notification to activity

I have an activity named Player Activity in which I am streaming music with the help of MediaPlayer API. Whenever my activity is created a notification is displayed which has some basic control of the music player.
So when I tap on my notification it jumps back to the Player Activity, but the state of the activity is lost.
Before tapping on notification :
After tapping on notification :
Here is the code of my notification's Pending Intent
Intent notifyIntent = new Intent(context, PlayerActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
notifyIntent.setAction("android.intent.action.MAIN");
notifyIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Here is the code for PlayerActivity.java :
package com.example.user.musicplayer;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.concurrent.TimeUnit;
import de.hdodenhof.circleimageview.CircleImageView;
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener{
private static Button btn_play_pause;
private Button btnToggleRepeat;
private Button btnStop;
private SeekBar seekBar;
private TextView textView;
public static MediaPlayer mediaPlayer;
private int mediaFileLength;
private int realtimeLength;
private String musicUrl;
private String imageUrl;
final Handler handler = new Handler();
private boolean isRepeat;
private CircleImageView musicImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Log.d("TAG", "onCreate");
NotificationGenerator.customBigNotification(getApplicationContext());
musicUrl = getIntent().getStringExtra("musicUrl");
imageUrl = getIntent().getStringExtra("imageUrl");
seekBar = (SeekBar)findViewById(R.id.seekbar);
seekBar.setMax(99); // 100% (0~99)
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaPlayer.isPlaying())
{
SeekBar seekBar = (SeekBar)v;
int playPosition = (mediaFileLength/100)*seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
}
return false;
}
});
textView = (TextView)findViewById(R.id.txtTime);
btnToggleRepeat = findViewById(R.id.btnRepeat);
btnStop = findViewById(R.id.btnStop);
musicImage = findViewById(R.id.musicImgView);
Picasso.get().load(imageUrl).placeholder(R.drawable.music).error(R.drawable.music).into(musicImage);
btn_play_pause = (Button) findViewById(R.id.btnTogglePlay);
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(PlayerActivity.this);
AsyncTask<String,String,String> mp3Play = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait");
mDialog.show();
}
#Override
protected String doInBackground(String... params) {
try{
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
}
catch (Exception ex)
{
}
return "";
}
#Override
protected void onPostExecute(String s) {
mediaFileLength = mediaPlayer.getDuration();
realtimeLength = mediaFileLength;
if(!mediaPlayer.isPlaying())
{
playMusic();
}
else
{
pauseMusic();
}
updateSeekBar();
mDialog.dismiss();
}
};
mp3Play.execute(musicUrl); // direct link mp3 file
}
});
btnToggleRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isRepeat){
isRepeat = false;
mediaPlayer.setLooping(false);
btnToggleRepeat.setText("Repeat");
}
else{
isRepeat = true;
mediaPlayer.setLooping(true);
btnToggleRepeat.setText("Single");
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.pause();
mediaPlayer.stop();
}
catch (Exception e){
Toast.makeText(PlayerActivity.this, "Opps! sorry something bad happened", Toast.LENGTH_SHORT).show();
}
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
public void pauseMusic() {
mediaPlayer.pause();
btn_play_pause.setText("Play");
}
public void playMusic() {
mediaPlayer.start();
btn_play_pause.setText("Pause");
}
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d",TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", "onResume");
}
#Override
protected void onStart() {
super.onStart();
Log.d("TAG", "onStart");
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
if(!mediaPlayer.isLooping())
btn_play_pause.setText("Play");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("notificationPlayer","Received Cancelled Event");
}
}
}
Thanks in advance. Pardon me if the explanation is not clear, because if i might have right words to explain it, I would have googled it.
Add this to your PlayerActivity activity in manifest :
android:launchMode="singleTask"
And use these flags in the intent for pendingintent :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

TTS remaining null

TTS object tts is always remaining null.
onInit always shows the toast message failed.
I have tried all other methods of creating onInitlistener as a separate method.
But the status code of onInit always remains -1 ie the value of error.
Please Help!!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpeechButton = (Button) findViewById(R.id.speechButton);
mSpeechButton.setEnabled(false);
mSpeechTextView = (TextView) findViewById(R.id.speechText);
// Hide the ActionBar
getActionBar().hide();
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.getDefault());
mSpeechButton.setEnabled(true);
mTrue = true;
} else {
mTrue = false;
Toast.makeText(getApplicationContext(), "Failed",
Toast.LENGTH_LONG).show();
}
}
});
mSpeechButton.setOnClickListener(this);
}
package com.example.textspeech;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
public class MainActivity extends Activity {
TextToSpeech mTextToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextToSpeech = new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
mTextToSpeech.setLanguage(Locale.UK);
mTextToSpeech.speak("You will use Eclipse IDE to create an Android application and name it as TextToSpeech under a package", TextToSpeech.QUEUE_FLUSH, null);
}
});
}
}

Android speech Recognition App Without Pop Up

I'm currently looking into getting a career with JAVA and have decided to start by building an app.
I have this code right here that I am using to trigger Speech Recognition.
public class MainActivity extends Activity implements OnClickListener{
private static final int VR_REQUEST = 999;
private ListView wordList;
private final String LOG_TAG = "SpeechRepeatActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById (R.id.word_list);
PackageManager packManager= getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities
(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (intActivities.size() !=0){
speechBtn.setOnClickListener(this);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this,"Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
if (v.getId() == R.id.speech_btn) {
listenToSpeech();
}
}
private void listenToSpeech() {
//start the speech recognition intent passing required data
Intent listenIntent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//indicate package
listenIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
getClass().getPackage().getName());
//message to display while listening
listenIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say a word!");
//set speech model
listenIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//specify number of results to retrieve
listenIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
//start listening
startActivityForResult(listenIntent, VR_REQUEST);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
//check speech recognition result
if (requestCode == VR_REQUEST && resultCode == RESULT_OK) {
//store the returned word list as an ArrayList
ArrayList<String> suggestedWords = data.
getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//set the retrieved list to display in the ListView
//using an ArrayAdapter
wordList.setAdapter(new ArrayAdapter<String>
(this, R.layout.word, suggestedWords));
}
//this detects which one the user clicks
wordList.setOnItemClickListener(new OnItemClickListener(){
//click listener for items within list
public void onItemClick(AdapterView<?> parent,
View view, int position, long id){
//cast the
TextView wordView = (TextView)
//retrive the chosen word
String wordChosen= (String) wordView.
//output for debugging
Log.v(LOG_TAG, "chosen:" +wordChosen);
}});
super.onActivityResult(requestCode, resultCode, data);
}
}
In this app the user presses a button and gets displayed with the Google Voice Input screen where you can click a button (it actually goes automatically) and you can speak, it will stop and it will display it. I don't want that window to pop up at all though. Instead just let the user click the button and be able to speak and let the app stop and display the text automatically (it already does that).
PLEASE! I understand that there are already answers on the form showing how to do this, in fact a user name JEEZ posted some code right here.
I don't know if I understood where to put this in my project file. I AM A NOOB! If anyone could help clarify this I would GREATLY appreciate your help.
Here is my code:
package com.example.speechrecognizertest;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
private static final int VR_REQUEST = 999;
public static final String TAG = null;
private ListView wordList;
private final String LOG_TAG = "SpeechRepeatActivity";
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speechBtn = (Button) findViewById(R.id.speech_btn);
wordList = (ListView) findViewById(R.id.word_list);
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
if (!mIslistening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
} else {
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
//Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
//Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> suggestedWords = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
wordList.setAdapter(new ArrayAdapter<String>(this, R.layout.word, suggestedWords));
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
AndroidManifest.xml
Add the following permission:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
class members
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent;
private boolean mIslistening;
In onCreate
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.........
.........
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
SpeechRecognitionListener listener = new SpeechRecognitionListener();
mSpeechRecognizer.setRecognitionListener(listener);
}
in your button listener just use this code
if (!mIsListening)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
In onDestroy
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
Inside your activity create the inner class
protected class SpeechRecognitionListener implements RecognitionListener
{
#Override
public void onBeginningOfSpeech()
{
//Log.d(TAG, "onBeginingOfSpeech");
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech");
}
#Override
public void onError(int error)
{
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
//Log.d(TAG, "error = " + error);
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}
#Override
public void onResults(Bundle results)
{
//Log.d(TAG, "onResults"); //$NON-NLS-1$
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// matches are the return values of speech recognition engine
// Use these values for whatever you wish to do
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
EDIT 2015-02-07: Incorporated code from the answers to this question by ZakiMak and Born To Win into the code in this answer to make this one more complete.
Don't Forget to add permission of following:-
<uses-permission android:name="android.permission.RECORD_AUDIO" />
It's been a long time since the post. Still for those who are looking, the above code provided by Hoan is almost complete, but there is an important line missing. Both in question and answer and I am not sure how it could work without that.
You need to create the SpeechRecognitionListener and set it as a listener for the SpeechRecognizer. Also it has to be done before we make a call to startListening() method of the SpeechRecognizer.
SpeechRecognitionListener listener = new SpeechRecognitionListener();
mSpeechRecognizer.setRecognitionListener(listener);
Then you also need to remove the listener from the onError event.
I ran into that issue as well. It seems like having startActivityForResult(...) will enable the pop-up mic, then you can handle the response in onActivityResult(). However, simply adding that startActivityForResult messed up my startListening(mSpeechRecognizerIntent), so you may need to do more adjustment.
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
startActivityForResult(recognizerIntent, 100);
// call back
onActivityResult(int requestCode, int resultCode, Intent data){...}

Categories