I'm using the BackGroundSound service music, but when I press the homebutton or power button or exiting the app the music just doesn't stop, and I need it to stop, Anyone have any suggestions/ideas how to fix it? I used this guide https://www.simplifiedcoding.net/android-service-example/
public class Backgroundsoundservice extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.backgroundmusic01);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
#SuppressLint("WrongConstant")
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
player.stop();
}
public void onPause()
{
player.pause();
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Try overriding onPause like this.
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null){
mediaPlayser.stop();
if (isFinishing()){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
Related
I created a game.I added some background music to the app and now I want to pause the music when the app is exited using home button and the song should resume when it is opened from the multitasking.
package tssll8.coloursmash;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
Import android.os.IBinder;
/**
* Created by ciddarth on 04/07/17.
*/
public class bgmusic extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.bg);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Mediaplayer has a pause() method: MediaPlayer#pause()
so you could call that in the on pause which gets triggered by pressing the home button, like so
public void onPause() {
player.pause();
}
and resume it in onResume like this:
public void onResume() {
player.play();
}
I have a service, which plays background music in all of my app's activities.
In every activity I added:
public void onPause() {
super.onPause();
stopService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onStop() {
super.onStop();
stopService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onResume() {
super.onResume();
startService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onRestart() {
super.onRestart();
startService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
My purpose was to stop or resume service which plays music when I close the app or turn off the screen. But It also stops when I switch to another activity.
Should I change something in my service's code?
Finally: I would like my service playing music to stop on screen turn off or app closing but not during activities switching.
Service:
public class MyService extends Service {
private final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
protected void onStop() {
player.pause();
}
public void onPause() {
player.pause();
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Try this in your Activity's onDestroy Method...
#Override
protected void onDestroy() {
super.onDestroy();
if(isMyServiceRunning(MyService.class))
{
stopService(new Intent(this, MyService.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Here when the Activity is finished you should stop the service..
Also in your service you should release the mediaplayer
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null){
mediaPlayser.stop();
if (isFinishing()){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
How to make service (background music) to turn off when I close the app or turn off the screen, but not when I switch to another activity?
Currently Music plays fine, I lasts until the screen turn off or I close the app, but also close when I switch to another activity. It is probably caused by onStop and onPause assigned to every activity. Please help me solve this issue
My service:
public class MyService extends Service {
private final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music;
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
protected void onStop() {
player.pause();
}
public void onPause() {
player.pause();
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
My example activity has this:
public void onPause() {
super.onPause();
stopService(new Intent(a.this, MyService.class));
}
public void onStop() {
super.onStop();
stopService(new Intent(a.this, MyService.class));
}
public void onResume() {
super.onResume();
startService(new Intent(a.this, MyService.class));
}
public void onRestart() {
super.onRestart();
startService(new Intent(a.this, MyService.class));
}
There are two ways i can suggest
1) let it be in onPause(), create a flag/boolean that will set to false by default and will be true in every-case such as new activity startup, on back press etc. so if onPause is called and flag is false you can stop the music.
2) you have background service already, you can keep checking which activity is in foreground, if is homeScreen you can stop the music.
Edit :- to know if your app is not in the foreground
check this link
this is good example
Use this code.
Remove this line:
player.pause();
public class MyService extends Service {
private final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.music;
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
protected void onStop() {
//player.pause();
}
public void onPause() {
//player.pause();
}
#Override
public void onDestroy() {
//player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
I read docs at Android Developer and still cant pause my service and then start it from the paused state (Playing the song).
With my current code, it always restart from the beginning of the song, but I would like to restart where the song was paused (with the stopClick).
Now I understand problem. In the MainActivity using stopService() method fully destroys it.
So how could i say service to wait when i press stop button to pause?
The Service class:
public class BackgroundSoundService extends Service {
MediaPlayer player;
int currentPos;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
final int MAX_VOLUME = 100;
player = MediaPlayer.create(this, R.raw.lightmusic);
player.setLooping(true);
float soundVolume = 77;
final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math
.log(MAX_VOLUME)));
player.setVolume(volume, volume);
player.seekTo(currentPos);
player.start();
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.seekTo(currentPos);
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
player.seekTo(currentPos);
player.start();
}
#Override
public void onRebind(Intent intent) {
player.seekTo(currentPos);
player.start();
super.onRebind(intent);
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
currentPos = player.getCurrentPosition();
player.pause();
}
public void onPause() {
currentPos = player.getCurrentPosition();
player.pause();
}
#Override
public void onDestroy() {
currentPos = player.getCurrentPosition();
player.pause();
//player.release();
}
#Override
public void onLowMemory() {
}
}
And my main Activity:
public class MainActivity extends QuizActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
startService(new Intent(this, BackgroundSoundService.class));
}
public void stopClick(View v) {
stopService(new Intent(this, BackgroundSoundService.class));
}
public void playClick(View v) {
startService(new Intent(this, BackgroundSoundService.class));
}
#Override
protected void onResume() {
super.onResume();
}
}
I implemented everything I've found here, but my service is not starting yet.
What I need to do is to start playing a radio station when the user clicks on a button, and only stop it when he clicks it again. I don't want the radio to be stopped if the application get closed.
When I test the code I'm sending, nothing happens.
Manifest:
<service
android:name=".RadioService"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:exported="false"
>
</service>
Service Code:
package com.po.portelaonline.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class RadioService extends Service {
Player player;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate(){
player = new Player();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy(){
player.stopThread();
}
}
Player class code:
package com.po.portelaonline.service;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import com.po.portelaonline.classes.Util;
class Player extends Thread {
volatile boolean running = true;
#Override
public void run() {
MediaPlayer player = new MediaPlayer();
try {
player.setDataSource(Util.getRadioUrl());
player.setOnPreparedListener(oplPlayer);
player.prepareAsync();
while (running) {
Player.sleep(500);
}
player.release();
player = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopThread() {
running = false;
}
OnPreparedListener oplPlayer = new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
};
}
And I'm calling this way:
Intent i = new Intent(getApplicationContext(), RadioService.class);
if(getApplicationContext().startService(i) == null){
findViewById(R.id.btnPlayStop).setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.stop));
}else{
getApplicationContext().stopService(i);
findViewById(R.id.btnPlayStop).setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.play));
}
Try this code for service class.
You don't need to create MediaPlayer object in separate thread. player.prepareAsync(); is already asynchronous.
EDIT:
The path to the RadioService class into the AndroidManifest.xml should be absolute: android:name="com.po.portelaonline.service.RadioService"
public class RadioService extends Service implements OnPreparedListener, OnErrorListener{
MediaPlayer mPlayer;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startPlayer();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate(){
initMediaPlayer();
}
private void initMediaPlayer () {
mPlayer = new MediaPlayer();
mPlayer.setOnPreparedListener(this);
mPlayer.setOnErrorListener(this);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
}
private void startPlayer(){
player.setDataSource(Util.getRadioUrl());
player.prepareAsync();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy(){
mPlayer.release();
}
#Override
public void onPrepared (MediaPlayer mp) {
mp.start();
}
#Override
public boolean onError (MediaPlayer mp, int what, int extra) {
Log.e("RadioService OnError", "what="+what+" extra="+extra);
return false;
}
}
i guess it should be
if(getApplicationContext().startService(i) != null)
instead of if(getApplicationContext().startService(i) == null)
You are immediately stopping the service after you start it.