Answer the question
In order to leave comments, you need to log in
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();
}
}
startService(new Intent(this, MyService.class));
// свернули приложение
@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)); // запустить песню
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question