Stop media player MP3 when back button pushed - android

My code works fine except when you press the back button.
The MP3 file called "testing" stops playing when I push the stop button and the audio check screen goes back to my menu screen. Perfect... all works great until I test the code on my phone. When I exit using the the phone's back button on my Android phone (not the stop button on my app) the media player keeps playing. I tried all the code and viewed every pertinent question. I implemented code using onStop onPause finish keyevent.KEYCODE_BACK and so forth, nothing works. I'm stumped.
Here is my code. How can I stop this MP3 by pressing the Android back button relative to this code?
public class Audio_Check extends Activity{
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
public class Audio_Check extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_check);
final MediaPlayer buttonSound = MediaPlayer.create(Audio_Check.this, R.raw.testing);
Button stbutton = (Button) findViewById(R.id.startbutton);
stbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonSound.start();
}
});
Button spbutton = (Button) findViewById(R.id.stopbutton);
spbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonSound.stop();
buttonSound.release();
Intent openE1 = new Intent("com.myapp.mysite.MENU");
startActivity(openE1);
}
});
}
}

Put this method,
#Override
protected void onDestroy() {
super.onDestroy();
buttonSound.stop();
buttonSound.reset();
buttonSound.release();
buttonSound = null;
}
Hope it will work.

I implemented code using onStop onPause finish keyevent.KEYCODE_BACK
and so forth, nothing works
There's no need to implement this in onPause or onStop, just override the back button and stop your media player and finish your activity.
#Override
public void onBackPressed(){
if(buttonSound != null && buttonSound.isPlaying())
buttonSound.stop();
finish();
}
If you're using an API lower than 5 :
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(buttonSound != null && buttonSound.isPlaying())
buttonSound.stop();
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}

I couldn't sleep. Kept coding and researching all night until I got it to work.
IT WORKED! But I had to figure out the next step based on verbose error messages while running. I had to take out the "final and MediaPlayer" or I would get a forced shutdown from Eclipse when I ran it through the simulator. No errors showed up while compiling the code.
MediaPlayer buttonSound ; // declared above first #Override
// code after that
// changed code from this
final MediaPlayer buttonSound = MediaPlayer.create(Audio_Check.this, R.raw.testing);
// to this
buttonSound = MediaPlayer.create(Audio_Check.this, R.raw.testing);
// and it works
Thank you

NOW IT WORKS... Here was the problem
note where the buttonSound.start(); was placed in my original code? It was above the });
When I put it below the }); it worked. Apparently it was protected before but now it works fine.
buttonSound = MediaPlayer.create(Audio_Check.this, R.raw.testing);
Button stbutton = (Button) findViewById(R.id.stbutton);
stbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
buttonSound.start();
// onDestroy goes right here

Related

remove all listeners while performing some actions

I have a button (named button1) with an OnClickListener and after button is clicked, a task should be execute, and button should become unclickable until task is finished. This is my code:
#Override
public void onClick(View v) {
removeListeners();
executeMyTask();
addListeners();
}
private void disableListeners() {
button1.setOnTouchListener(null);
button2.setOnClickListener(null);
}
private void enableListeners() {
button1.setOnTouchListener(this);
button2.setOnClickListener(this);
}
Now it happen that, if I click button while executeMyTask is running (so when listener is disabled), when task finish, onClick is called again.
I would that all clicks performed while executeMyTask is running will be ignored.
how can I do ?
Why don't you just disable the whole button with:
button1.setEnabled(false);
button2.setEnabled(false);
And later just re-enable them:
button1.setEnabled(true);
button2.setEnabled(true);
It will be easier for the users to understand that the button is un-clickable at the moment.
There are 2 ways:
1) With disable all other buttons,
#Override
public void onClick(View v) {
setButtonEnabled(false);
executeMyTask();
setButtonEnabled(true);
}
private void setButtonEnabled(boolean enable) {
// TODO Auto-generated method stub
btn_1.setEnabled(enable);
btn_2.setEnabled(enable);
btn_3.setEnabled(enable);
}
2) Use a boolean to keep record of async task running or not:
Like:
#Override
public void onClick(View v) {
removeListeners();
executeMyTask();
addListeners();
}
// And in executeMyTask
onPreExecute(){
....
..
isAsyncRunning = true;
..
....
}
onPostExecute(){
....
..
isAsyncRunning = false;
..
....
}
//And in Button Click Listeners
{
if(!isAsyncRunning){
// Do something...
}
}

Android calculator with single edit text displaying complete input and output

I want to display the complete input and output of my app.
For example:
2+2=4 needs to be displayed after clicking "=" in the calculator.
My problem is that app closes unexpectedly.
package com.scientific.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ToggleButton;
public class Calculator extends Activity{
EditText display;
Button btn,btnop,add,sub,mul,div;
ToggleButton shift;
String operator,result;
float value=0;
Character op = 'q';
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
display = (EditText)findViewById(R.id.etDisplay);
shift = (ToggleButton)findViewById(R.id.tbShift);
}
public void set_number(View v) {
// TODO Auto-generated method stub
btn = (Button)findViewById(v.getId());
result = display.getText().toString();
display.setText(result+btn.getText().toString());
}
public void btnplusclicked(View v){
perform(v);
op = '+';
}
public void btnminusclicked(View v){
perform(v);
op = '-';
}
public void btndivideclicked(View v){
perform(v);
op = '÷';
}
public void btnmulticlicked(View v){
perform(v);
op = '×';
}
public void btnequalClicked(View v){
evaluate();
}
public void perform(View v) {
// TODO Auto-generated method stub
btnop=(Button)findViewById(v.getId());
result=display.getText().toString();
operator=btnop.getText().toString();
display.setText(result+operator);
}
private void evaluate() {
// TODO Auto-generated method stub
value=Float.valueOf(display.getText().toString());
if(op == '+')
value=Float.valueOf(display.getText().toString())+value;
else if(op == '-')
value=Float.valueOf(display.getText().toString())-value;
else if(op == '/')
value=Float.valueOf(display.getText().toString())/value;
else if(op == '*')
value=Float.valueOf(display.getText().toString())*value;
display.setText(String.valueOf(value));
}
}
It seems you are trying to parse '123+25' to float. so it will give error.
And what if user presses '1+2-3*4' what would be your operator '*' . so it might not work properly. please check here for a good example on calculator for android..
Try to understand this way. When you click equal to evaluate() is called.
In which the first line is value=Float.valueOf(display.getText().toString());
That is converting what is the display to Float.
Though computer is able to convert the first digits but when it come and reads the operator in between. It can't convert that. Hence the crash. Just to be assured.
Type 2 and then press equal I bet it won't crash.
Now either you can do is. When ever a operator ( + - * / ) is called. Use a float variable and calculate it and keep it in the memory. Once the user presses Equal to. Display that Value. Simple as it is.
For more reference Have a look at simple cal or complex calc

Text to speech unusual behaviour in android

I am having a strange experience with text to speech.
see my code:
Button b;
TextView title, body;
TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popups);
b = (Button) findViewById(R.id.buttonok);
title = (TextView) findViewById(R.id.textViewtitle);
body = (TextView) findViewById(R.id.textViewbody);
b.setText("ok");
title.setText(Receive.address);
body.setText(Receive.body);
tts = new TextToSpeech(Popup.this, new TextToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.US);
}
}
});
play();//this is not working??!!i don't know why
b.performClick();//even this is not working
/* but when i click this button it works??? how and why?*/
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play(); // Popup.this.finish();
}
});
}
private void play() {
// TODO Auto-generated method stub
tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);
}
My text to speech works fine only when i click the button but whenever i don't click this button and write the tts.speak() inside normal code it do not works...why?
regards charlie
You have to wait for onInit being called before you can start speak. In your code you call play() right after the declaration. onInit is a callback and it takes some time before it being called. If you click your button as soon as the button appears, sometime it will fail as onInit has not been called. You should have a class member boolean mIsReady and set it to true in onInit. And in your play() method
private void play() {
// TODO Auto-generated method stub
if (mIsReady) {
tts.speak(Receive.body, TextToSpeech.QUEUE_FLUSH, null);
}
}
b.performClick();//even this is not working
/* but when i click this button it works??? how and why?*/
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
play(); // Popup.this.finish();
}
});
You are performing a click with b.performClick() before setting its setOnClickListener. Also, you are better off making such calls on the onResume() method. OnCreate is meant to be used to bind views and prepare the activity. The onResume() method will be called before showing the view to the user on the foreground so that would be the best place to put this code.
Take a look at the activity lifecycle.

Android application retain the state after the app is restored from minimize

I have an app which starts from a splash screen and then navigates to other activities. If i press the home button in a particular activity ,the app gets minimized. Again if i click on the app icon, the app starts from the splash screen. I want to resume my app from the activity in which the home button was pressed. How to achieve this?
package com.xyz.user.login;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
public class ResetPasswordActivity extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
// Single menu item is selected do something
// Ex: launching new activity/screen or show alert message
PopIt("Are you sure you want to exit?");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void PopIt(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string)
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(
getApplicationContext(),
SignInActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reset_password);
ImageButton imgRPass=(ImageButton)findViewById(R.id.imgChangePass);
imgRPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent(ResetPasswordActivity.this,ResetPasswordMessageActivity.class);
startActivity(intent);
}
});
ImageButton imgBack=(ImageButton)findViewById(R.id.imgbtnBackFromResetPass);
imgBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
}
}
Maybe the code in your Activities has a call to finish() in onStop() or onPause(). That destroys the Activity when it's minimised and causes the app to start again. There are other steps to take to be sure of restoring the state, but that is a good place to start looking.
You could try putting this code in there to track what is going on.
private static final String TAG = "ResetPasswordActivity";
#Override public void onStart() {
Log.d(TAG, "onStart:");
super.onStart();
}
#Override public void onResume() {
Log.d(TAG, "onResume:");
super.onResume();
}
#Override public void onPause() {
Log.d(TAG, "onPause:");
super.onPause();
}
#Override public void onStop() {
Log.d(TAG, "onStop:");
super.onStop();
}
#Override public void onDestroy() {
Log.d(TAG, "onDestroy:");
super.onDestroy();
}
There are calls to finish and startActivity in there, although I cannot see why they should be executed. I'd put a Log statement by each. Then try it again and see what the Logcat output says when you minimise and relaunch the app.
You are talking about the default behavior of android. when you press home button app get minimized and when you click on app icon, by default app start from the same screen because its in pause mode and running in background. however you are getting splash screen on next launch that means your activity is getting killed by somehow either by android(due to memory constraint) or its getting a crash. see your logcat for details.
Write in AndroidManifest.xml to every activity option android:launchMode="singleTop".
Make sure you don't have android:noHistory="true" in your activity tag of manifest file. With it Android doesn't keep activity state when you minimizing your app

Change Text in TextView Box when Button is pressed

I'm fairly new to programming and I am learning to develop in Java and building Android applications.
I am trying to create a Dreidel game, on my xml file, I have a button, an imageview, and a TextView (I will be working on keeping the score a little later, I can figure that out on my own easily enough I imagine).
But the objective is that when I push the button, a random number generator produces a number from 0-3,
If 0, I want the TextBox to display "You get nothing"
If 1, I want the TextBox to display something else
If 2, I want the TextBox to display something else
If 3, I want the TextBox to display something else
Here is the code. When I run it in the Android Emulator, it starts up but nothing happens when I click the button
package com.secondtry;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
numGen.nextInt(4);
if (numGen.nextInt() == 0)
{
display.setText("You get nothing");
}
else if (numGen.nextInt() == 1)
{
display.setText("You get half!");
}
else if (numGen.nextInt() == 2)
{
display.setText("You get it all");
}
else if (numGen.nextInt() == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
Use numGen.nextInt(4) instead of numGen.nextInt() in your condition. Grab its value inside a variable(say x) and use that value in every condition.
You may try this:
int ran = numGen.nextInt(4);
switch (ran){
case 0:
display.setText("You get nothing");
break;
case 1:
display.setText("You get half!");
break;
case 2:
display.setText("You get it all");
break;
case 3:
display.setText("Chip in a coin");
break;
}
You need to either define your button in onCreate with something like
final Button spinButton = (Button) findViewById(R.id.spinbuttonIdInXML);
Or pull the onClick outside of the onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
...
}
#Override
public void onClick(View v) {
...
}
Define your Button in OnCreate Like this..
spinButton = (Button)findViewById(R.id.urbuttonid);
updated try this
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinButton = (Button)findViewById(R.id.ButtonId);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(4);
if (rNumber == 0)
{
display.setText("You get nothing");
}
else if (rNumber == 1)
{
display.setText("You get half!");
}
else if (rNumber == 2)
{
display.setText("You get it all");
}
else if (rNumber == 3)
{
display.setText("Chip in a coin");
} }
});
}
}

Categories

Resources