K
K
katavagner2015-05-06 15:32:45
Java
katavagner, 2015-05-06 15:32:45

How to pause background music in an app?

There is a class for creating background music:

public class MyService extends Service {
    MediaPlayer player;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        player = MediaPlayer.create(this, R.raw.fon);
        player.setLooping(true); // зацикливаем
    }

    @Override
    public void onDestroy() {
        player.stop();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        player.start();
    }
}

Next, on the very first screen (loading screen), I launch the player and the music starts working in all windows:
startService(new Intent(this, MyService.class));
Next, in each class, I write the following code to stop the music after the application is minimized:
// свернули приложение
    @Override
    public void onPause() {
        Play.super.onPause();
        stopService(new Intent(this, MyService.class)); // остановить песню
    }

    // развернули приложение
    @Override
    public void onResume() {
        Play.super.onResume();
        startService(new Intent(this, MyService.class)); // запустить песню
    }

It turns out that every time the application is minimized / maximized, the music starts playing again (this is understandable, because I restart the class)
Question: how can I pause the background melody after the user minimizes the application and continue the song from the same place after expanding?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
one pavel, 2015-05-06
@onepavel

You don't need to call stopService in onPause, you are killing the service.
You should call startService(new Intent(this, MyService.class),putExtra("pause", true));
with the parameter that you catch in the service.
In the service in the onStartCommand method, check for the presence of a parameter
if intent.getBooleanExtra("pause", false) == true then player.pause()
Read developer.android.com/guide/components/services.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question