Thredge Paul
Thredge Paul

Reputation: 55

How to stop service when home button pressed?

I'm currently working on a mobile app as a final project in my course. My problem here is the background music I play using Service didn't stop when I pressed the HOME button of the phone.

BgMusicService.class

package com.example.biowit;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class BgMusicService extends Service {
MediaPlayer player;

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

@Override
public void onCreate() {

    super.onCreate();
    player = MediaPlayer.create(this, R.raw.bg_music);
    player.setLooping(true);
    player.setVolume(100, 100);
    player.setOnCompletionListener(mp -> player.release());
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    player.start();
    player.setOnCompletionListener(mp -> player.release());
    return super.onStartCommand(intent, flags, startId);

}


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

@Override
public void onLowMemory() {
    super.onLowMemory();
}

}

No ERROR LOG detected

Upvotes: 0

Views: 421

Answers (1)

Vojin Purić
Vojin Purić

Reputation: 2376

Inside your Activity lifecycle methods call intent that will start/stop service, or even better instead of start/stopping whole service just send intent to play pause music and keep service running.

Depending on your app structure either go for onPause/onResume or onStart/onStop

Upvotes: 0

Related Questions