I am new at Android and working on a speech to text app. I am using Google API. I want to allow users can only speak 2 seconds. After 2 seconds pop-up window should close. Can anyone give me some tips?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
public void promptSpeechInput()
{
//This intent recognize the speech
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say Something");
try {
startActivityForResult(i, 100);
}
catch (ActivityNotFoundException a)
{
Toast.makeText(MainActivity.this,"Your device does not support",Toast.LENGTH_LONG).show();
}
}
//For receiving speech input
public void onActivityResult(int request_code, int result_code, Intent i)
{
super.onActivityResult(request_code, result_code, i);
switch (request_code)
{
case 100: if(result_code == RESULT_OK && i != null)
{
ArrayList<String> result = i.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
resultTEXT.setText(result.get(0));
}
break;
}
}
You can add this code where you want to start the timer and in method run you have to write the code for closing the pop up
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
5000
);
Here it is 5 seconds (5000 milliseconds) you can change it to whatever time period you required in milliseconds.
Try Handler inside UIThread this lets you delay when the pop-up window closes..add the code to close the pop-up in run():
runOnUiThread(new Runnable() {
#Override
public void run() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//close the window pop-up here
}
}, 2000);
}
});
hope it helps
Related
I try to run a method in my service every two seconds, but when i start the services just run one time
This is the relevant code:
the start service:
mViewHolder.mLinearLayoutContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent launchIntent = view.getContext().getPackageManager().getLaunchIntentForPackage(mListStorage.get(position).getAdrress());
mApkPackage = mListStorage.get(position).getAdrress();
Intent intent = new Intent(view.getContext(), KillerService.class);
if(mApkPackage != null){
intent.putExtra("NAMEAPK", mApkPackage);
view.getContext().startService(new Intent(view.getContext().getApplicationContext(), KillerService.class));
view.getContext().bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
}
if (launchIntent != null) {
view.getContext().startActivity(launchIntent);//null pointer check in case package name was not found
}
}
});
And this is from my Service class:
#Override
protected void onHandleIntent(#Nullable Intent intent) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//mAppsNames();
Log.d("SYSTEMRUNNIGKILLI", "matandoapps");
}
}, 2000);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
mApkName = intent.getStringExtra("NAMEAPK");
Log.d("HOLAXD", mApkName);
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
The part of Log.d("SYSTEMRUNNIGKILLI", "matandoapps"); just run one time and not every 2 seconds.
You are using wrong method to call code after every 2 seconds . Try to use this method
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {}
}, 0, 1000); //1000 miliseconds equal to 1 second
Another way just add handler.postDelayed(this,2000);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//mAppsNames();
Log.d("SYSTEMRUNNIGKILLI", "matandoapps");
handler.postDelayed(this,2000);
}
}, 2000);
I'm trying to implement Bulk Scan mode in me.dm7.barcodescanner:zxing:1.9 library. This is my snippet codes. Im trying to do multiple scan which from the codes for now i just trying to display each of the scan result in messagedialogue. however, after the first scan resulthandler, the second time scan automatically kill the activity.
private ZXingScannerView mScannerView;
private boolean mFlash;
private boolean mAutoFocus;
private int mCameraId = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
setupFormats();
contentFrame.addView(mScannerView);
}
//i want to make my scanner able to keep scanning getting the result.
//however after the first scan, the second scan will automatically close the activity
#Override
public void handleResult(Result result) {
try {
if(!result.getText().equals("")){
//In message dialogue will have 1 button handle on onDialogPositiveClick
showMessageDialog("Contents = " + result.getText() + ", Format =
" + result.getBarcodeFormat().toString());
}
} catch (Exception e) {
} finally {
}
}
public void showMessageDialog(String message) {
DialogFragment fragment = MessageDialogFragment.newInstance("Scan
Results", message, this);
fragment.show(getSupportFragmentManager(), "scan_results");
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
mScannerView.resumeCameraPreview(this);
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
closeMessageDialog();
closeFormatsDialog();
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera(mCameraId);
mScannerView.setFlash(mFlash);
mScannerView.setAutoFocus(mAutoFocus);
}
Try it with onActivityResult
/*Here is where we come back after the Barcode Scanner is done*/
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_FORMATS", "PRODUCT_MODE,CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF");
startActivityForResult(intent, 0); // start the next scan
} else if (resultCode == RESULT_CANCELED) {
//do whatever else you want.
}
}
}
you have to add handler or TimerTask for secondTime Scan.after get first scan result in handleResult you have to start scanning again after some delay, whatever delay you want add to handler.
#Override
public void handleResult(final Result rawResult) {
runOnUiThread(new Runnable() {
#Override
public void run() {
handleDecode(rawResult);
}
});
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScannerView.resumeCameraPreview(CaptureActivity.this);
}
}, 4000);// 4 sec delay to restart scan again.
}
I have a long running operation. Inside a thread I start a new activity like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(MainActivity.this,MainActivity.class));
}
});
}
}).start();
}
The problem is when I run another app and the thread finishes, that activity appears on the top of the screen. How to force that activity not to apear on the top?
you can use like below..
Handler splashHandler;
splashHandler = new Handler();
splashHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent loginIntent = new Intent(Splash.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
}, 2000);
#Override
public void onBackPressed() {
super.onBackPressed();
if (splashHandler != null)
splashHandler.removeCallbacksAndMessages(null);
}
#Override
protected void onResume() {
super.onResume();
if (splashHandler != null)
splashHandler.removeCallbacksAndMessages(null);
}
This happens because you're getting the Context out of the "other app". You should pass in the application context rather than a context from the local activity. Use context.getApplicationContext() and save that in a local variable, then use this context to start the activity
The code should be something like this:
#Override
protected void onPostExecute(List<VideoDataDescription> result) {
super.onPostExecute(result);
MainActivity.progressDialog.dismiss();
context.startActivity(new Intent(context, MainActivity.class));
}
}
you'd call it like this:
new MyTask(context).execute();
I'm making a quiz app in which there is a sound game.But i find that sound keeps playing even when app is closed. Two time I'm using mediaplayer.
1.while clicking on image button.
2.on changing question.
Question is changed every 15 sec and after killing app sound is getting played every 15 seconds.
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
#Override
protected void onResume()
{
super.onResume();
questionPlay = db.getMorseQuestionMode(mode);
totalQuestion = questionPlay.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int QusId = this.getResources().getIdentifier(questionPlay.get(index).getQus().toString(), "raw", getPackageName());
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mCountDown.start();
mediaPlayer= MediaPlayer.create(this,QusId);
mediaPlayer.start();
} else {
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mCountDown.cancel();
if (index < totalQuestion) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())) {
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else {
vibrator.vibrate(50);
showQuestion(++index); // If choose right , just go to next question
}
txtScore.setText(String.format("%d", score));
}
}
//CLicking back Button
public void onBackPressed() {
showExitAlertBox();
}
public void showExitAlertBox() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("You want to quit the play?");
//Yes Quit then go to category page
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int button) {
Intent intent = new Intent(getApplicationContext(), CategorySecond.class);
startActivity(intent);
}
});
//no Quit stay on same page
alertDialog.setNegativeButton("NO", null);
alertDialog.show();
mediaPlayer.stop();
}
}
Error Showing us below
W/MediaPlayer-JNI: MediaPlayer finalized without being released
Cancel your timer and stop mediaplayer if playing in onStop
#Override
public void onStop() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
if(mCountDown != null)
mCountDown.cancel();
super.onStop();
}
handle on destroy
#Override
public void onDestroy() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
if(mCountDown != null)
mCountDown.cancel();
}
You have not released the mediaplayer properly.
Use
protected void onStop(){
mediaPlayer.release();
mediaPlayer = null;
}
call this method where ever required.
I am creating an app that vibrate and beep every 30 sec and when I log out the vibrate and beep must be cancelled and when I log in the vibrate and beep should resume.
NOTE: it must vibrate and beep for every 30 sec until I log out
In my app I am using TimerTask for this implementation
this is the code for vibrate and beep using TimerTask
static TimerTask Task;
final static Handler handler = new Handler();
static Timer t = new Timer();
public static void vib() {
Task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Vibrator vibrator = (Vibrator) ApplicationUtils.getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(3000);
playSound();
Log.d("TIMER", "Timer set on");
}
});
}
};
t.schedule(Task, 0, 30000);
}
This is the code I'm using in logout section
public void stopvib() {
if (Task != null) {
// Log.d("TIMER", "timer canceled");
t.cancel();
Task.cancel();
}
}
Note: I also removed the Task.cancel(); but still I am getting same error
My vibrate working fine before logout and again login I am geting error
java.lang.IllegalStateException: Timer was cancelled
at java.util.Timer.scheduleImpl(Timer.java:562)
at java.util.Timer.schedule(Timer.java:481)
at com.vib(AlertListActivity.java:724)
can any one help me with this coding. Where did I go wrong?
i have recently run this code and is working fine. This can be achieved using broadcast Receiver.You have to implement separate CustomTimer task that extend TimerTask:
Activity mActivity=null;
public MyCustomTimer(Activity mActivity) {
this.mActivity=mActivity;
}
#Override
public void run() {
this.mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mActivity, "Write you code here",Toast.LENGTH_LONG).show();
Log.d("MyCustomTimer","Call");
}
});
}
After this you have to implement BroadCast Receive in that class where you want to implement " vib() " method.:
Let say, in my case (just for example ) is MainActivity:
public class MainActivity extends Activity {
private MyCustomTimer myCustomTimer = null;
BroadcastReceiver mBr_Start = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("START_VIBRATION")) {
System.out.println("onreceive :START_VIBRATION");
vib();
}
}
};
BroadcastReceiver mBr_Stop = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("STOP_VIBRATION")) {
stopVibration();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction("START_VIBRATION");
registerReceiver(mBr_Start, mIntentFilter);
IntentFilter mIntentFilter2 = new IntentFilter();
mIntentFilter2.addAction("STOP_VIBRATION");
registerReceiver(mBr_Stop, mIntentFilter2);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, MySecondActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void vib() {
myCustomTimer = new MyCustomTimer(MainActivity.this);
Timer timer = new Timer();
timer.scheduleAtFixedRate(myCustomTimer, 0, 30000);
}
private void stopVibration() {
Log.d("MainActivity", "Before Cancel");
if (null != myCustomTimer)
myCustomTimer.cancel();
Log.d("MainActivity", "After Cancel");
}
}
Now,you can start Or stop vibration by implementing these lines:
To start vibration:
Intent i=new Intent("START_VIBRATION");
mActivity.sendBroadcast(i);
To Stop:
Intent i=new Intent("STOP_VIBRATION");
mActivity.sendBroadcast(i);
Note:
onDestroy() of MainActivity (in your case,Where you implement Broadcast Receiver,unregister BroadcastReceiver.)
Set timer instance to null when you logout and then initialize it everytime user logged in the app. This will fix the "Timer was cancelled" related issues.
Why do you need a static TimerTask.You can give like this which works fine for me.
timer.schedule(new TimerTask() {
#Override
public void run() {
//your code
}
}, 0, 30000);
While logout use, timer.cancel().
Here you can simply cancel the timer.No need to cancel the TimerTask.