Stopping a media player - java

I am implementing a media player on android phone.
This player starts based on some conditions, but I am unable to stop it (back button pressing doesn't work). Once the streamer who is sending the data stops, player stops too and crashes.
I want to stop the media player whenever I want by pressing the BACK button. can somebody tell me how to do so?
I have tried using methods like these, but they don't work!!
#Override
public void onBackPressed()
{
MediaPlayer.stop();
MediaPlayer.release();
finish();
}
#Override
protected void onStop()
{
finish();
}

Try adding
MediaPlayer.release();
tou the activities onPause() method

put super.onStop() (super call) call in your onstop method.And also i think you don't want to call finish () method twice.when you back the activity and the activity disappears and onStop called.you can remove onStop call from onBackPressed method.

It should be smth like this:
private MediaPlayer mPlayer = ...; // define it somewhere
#Override
public void onBackPressed()
{
if(mPlayer != null && mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.release();
}
}
#Override
protected void onStop()
{
super.onStop();
if(mPlayer != null && mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.release();
}
}

Related

Adding music in android studio (java, MediaPlayer)

buttonMusic = findViewById(R.id.buttonMus);
musicSound = MediaPlayer.create(this, R.raw.music);
buttonClick();
}
private Button buttonMusic;
private MediaPlayer musicSound;
public void buttonClick() {
buttonMusic.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay(musicSound);
}
}
);
}
public void soundPlay(MediaPlayer sound) {
if (sound.isPlaying()) {
sound.stop();
}else {
sound.start();
sound.setLooping(true);
} }
Hello.
The code launches the music, is able to stop it, but it wont play again after pressing the play button, after pausing the song that is.
you aren't pausing song, you are stop()ing it. use sound.pause() for pausing :)
after stop() MediaPlayer you have to prepare it again, use prepare() or prepareAsync(). MediaPlayer.create( makes that for you at the beginning, also if you would create MediaPlayer using its constructor you would also want to prepare()/preapreAsync() before calling start() in onClick
check out state diagram of MediaPlayer

How to stop the sound/audio when you press the back button in the phone

how can i stop the audio from playing when i press the back button in my phone. when i go to another activity the audio is still playing unless i close the app. here's my code:
FloatingActionButton fab7 = (FloatingActionButton) this.findViewById(R.id.fab7);
final MediaPlayer mp = MediaPlayer.create( this, R.raw.cebu);
fab7.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {;
if(mp.isPlaying()){
mp.pause();
} else {
mp.start();
}
}
});
1.) declare MediaPlayer mp; outside onCreate
2.) override onStop and apply the same logic of click listener inside onStop
why onStop not onBackPress?
Because you want to pause the player when you go outside app as well as when you go to another activity
MediaPlayer mp;
onCreate(..){
mp = MediaPlayer.create( this, R.raw.cebu);
fab7.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {;
pausePlayer();
}
});
}
#Override
public void onStop(){
super.onStop()
pausePlayer();
}
void pausePlayer(){
if(mp.isPlaying()){
mp.pause();
} else {
mp.start();
}
}
#Override
public void onBackPress() {
pausePlayer();
mp.stop();
}
Use this to detect and pause the Mediaplayer
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "Back button pressed Song paused");
mp.pause();
}
return super.onKeyDown(keyCode, event);
}
write mediaplayer.stop();
on start of back activity when u gone
Override Activity#onBackPress() method to stop your player when pressing Back button:
#Override
public void onBackPress() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
If you want to stop your player when your Activity finish, and don't care why (may be Back press, another Activity started, app crashed,..), you can override Activity#onStop() so you will make sure your music is immediately stop whenever your Activity gone!
#Override
public void onStop() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
super.onStop();
}
Btw, note that you should use mp.stop() instead of mp.pause() then mp.release() to avoid memory/resources leak!

Terminating Android Timer if user doesn't use the App(Prevent running in the background)

I have a Timer in my App that infinitely runs an Animation. like this:
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//Running Animation Code
}
});
}
}, 1000, 1000);
Now I realized that this code runs even if user click Back Button of android. if fact it runs in the background and it seems uses a lot of memory.
I need this code run ONLY if user in the app. In fact when user click on Back Button, this Timer goes to end and if user clicks on Home Button, after a while that user doesn't use the App, terminates this Timer.
What I need is to prevent using memory. Because i realized if this codes runs a while, App freezes! I need a normal behavior.
If your Activity is the last element in the BackStack, then it will be put in the background as if you pressed the Home button.
As such, the onPause() method is triggered.
You can thus cancel your animation there.
#Override protected void onPause() {
this.timer.cancel();
}
You should as well start your animation in the onResume() method.
Note that onResume() is also called right after onCreate(); so it's even suitable to start the animation from a cold app start.
#Override protected void onResume() {
this.timer.scheduleAtFixedRate(...);
}
onPause() will be also called if you start another Application from your app (e.g: a Ringtone Picker). In the same way, when you head back to your app, onResume() will be triggered.
There is no need to add the same line of code in onBackPressed().
Also, what's the point in stopping the animation in onStop() or onDestroy()?
Do it in onPause() already. When your are app goes into the background, the animation will already be canceled and won't be using as much memory.
Don't know why I see such complicated answers.
You can do it like this, in onBackPressed() or onDestroy(), whatever suits you.
if (t != null) {
t.cancel();
}
If you need, you can start timer in onResume() and cancel it in onStop(), it entirely depend on you requirement.
If a caller wants to terminate a timer's task execution thread
rapidly, the caller should invoke the timer's cancel method. - Android Timer documentation
You should also see purge and
How to stop the Timer in android?
Disclaimer: This might not be the 100% best way to do this and it might be considered bad practice by some.
I have used the below code in a production app and it works. I have however edited it (removed app specific references and code) into a basic sample that should give you a very good start.
The static mIsAppVisible variable can be called anywhere (via your App class) in your app to check if code should run based on the condition that the app needs to be in focus/visible.
You can also check mIsAppInBackground in your activities that extend ParentActivity to see if the app is actually interactive, etc.
public class App extends Application {
public static boolean mIsAppVisible = false;
...
}
Create a "Parent" activity class, that all your other activities extend.
public class ParentActivity extends Activity {
public static boolean mIsBackPressed = false;
public static boolean mIsAppInBackground = false;
private static boolean mIsWindowFocused = false;
public boolean mFailed = false;
private boolean mWasScreenOn = true;
#Override
protected void onStart() {
applicationWillEnterForeground();
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
applicationDidEnterBackground();
}
#Override
public void finish() {
super.finish();
// If something calls "finish()" it needs to behave similarly to
// pressing the back button to "close" an activity.
mIsBackPressed = true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
mIsWindowFocused = hasFocus;
if (mIsBackPressed && !hasFocus) {
mIsBackPressed = false;
mIsWindowFocused = true;
}
if (!mIsWindowFocused && mFailed)
applicationDidEnterBackground();
if (isScreenOn() && App.mIsAppVisible && hasFocus) {
// App is back in focus. Do something here...
// this can occur when the notification shade is
// pulled down and hidden again, for example.
}
super.onWindowFocusChanged(hasFocus);
}
#Override
public void onResume() {
super.onResume();
if (!mWasScreenOn && mIsWindowFocused)
onWindowFocusChanged(true);
}
#Override
public void onBackPressed() {
// this is for any "sub" activities that you might have
if (!(this instanceof MainActivity))
mIsBackPressed = true;
if (isTaskRoot()) {
// If we are "closing" the app
App.mIsAppVisible = false;
super.onBackPressed();
} else
super.onBackPressed();
}
private void applicationWillEnterForeground() {
if (mIsAppInBackground) {
mIsAppInBackground = false;
App.mIsAppVisible = true;
// App is back in foreground. Do something here...
// this happens when the app was backgrounded and is
// now returning
} else
mFailed = false;
}
private void applicationDidEnterBackground() {
if (!mIsWindowFocused || !isScreenOn()) {
mIsAppInBackground = true;
App.mIsAppVisible = false;
mFailed = false;
// App is not in focus. Do something here...
} else if (!mFailed)
mFailed = true;
}
private boolean isScreenOn() {
boolean screenState = false;
try {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
screenState = powerManager.isInteractive();
} catch (Exception e) {
Log.e(TAG, "isScreenOn", e);
}
mWasScreenOn = screenState;
return screenState;
}
}
For your use you might want to create a method in your activity (code snippet assumes MainActivity) that handles the animation to call the t.cancel(); method that penguin suggested. You could then in the ParentActivity.applicationDidEnterBackground() method add the following:
if (this instanceof MainActivity) {
((MainActivity) this).cancelTimer();
}
Or you could add the timer to the ParentActivity class and then not need the instanceof check or the extra method.

android app crashes when starting/stopping media

I am writing a small practice app that plays a sound clip when a button is tapped. In my previous code, this amounts to just the creation of a MediaPlayer object and a call to mp.start() to start the audio.
This works, but now I would like that same button to play only when no sound is playing yet. If sound is playing, stop the audio. A play/stop button.
I tried to do this using the following code:
```
public class MainActivity extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goButtonClicked(View v) {
if(mp == null) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
if(mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
}
```
However now when I run the app, the app crashes when I tap the button. Where did I go wrong?
Just change your code like this,
public void goButtonClicked(View v) {
if(mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.wordt);
}
....
}
What happens here is, MediaPlayer mp = ... means you are creating a local variable inside if condition. But still your field variable is null. And when the app executes the second if condition, it throws a NullPointerException.
You didn't initialize your first mp object, so you see nullPointerException,
and you can delete second mp object

Resume song in Android

I have created a media player . I run the application properly. But I want to resume my song when I restart my activity. Why does my audio restart when I restart my activity?
How can I do this? I don't understand. Can any one help me??
Here is my code.
public class Audio_Activity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
if(mp!=null) {
length=mp.getCurrentPosition();
Log.e("Current ","Position -> " + length);
if(length > 0){
mp.seekTo(length);
mp.start();
btnChapter.setEnabled(false);
}
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
}
}
To prevent this you should use a service for playing sounds while your activity goes to background. Refer to the android's documentation about the life-cycle of an activity to see what actually happens: https://developer.android.com/training/basics/activity-lifecycle/index.html
Can you try:
mp.start();
mp.seekTo(length);
Referring to documentation of MediaPlayer:
public void start ()
Starts or resumes playback. If playback had previously been paused, playback will continue from where it was paused. If playback had been stopped, or never started before, playback will start at the beginning.
Save the mp.getCurrentPosition in a persistence of some sort, sharedprefs for instance in onPause, call pause() on the mediaplayer.
In onResume, do mp.start(), mp.seekTo(savedPosition).

Categories

Resources