当应用程序从 android studio 中最近的任务菜单中被终止时,我想播放背景音乐。
我尝试过使用后台服务...较低的设备应用程序工作正常,但在 Android 馅饼中,5 秒后歌曲将停止。
public class Myservice extends Service {
MediaPlayer mediaPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "service started successfully", Toast.LENGTH_SHORT).show();
mediaPlayer = MediaPlayer.create(this, animal);
mediaPlayer.setLooping(false);
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "Mediaplayer started", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
mediaPlayer.stop();
}
}
最佳答案
尝试阅读 Background Execution Limits和 Background Service Limitations .
从 Android 8(API 级别 26)开始,您的应用在后台运行时可以执行的操作存在后台限制:
Whenever an app runs in the background, it consumes some of the device's limited resources, like RAM. This can result in an impaired user experience, especially if the user is using a resource-intensive app, such as playing a game or watching video. To improve the user experience, Android 8.0 (API level 26) imposes limitations on what apps can do while running in the background.
就您而言,您的 Android 8 之前的设备可以使用后台服务运行并且可以正常工作。
但是对于任何搭载 Android 8 及更高版本的设备,您都无法执行此操作,因为系统会“终止”您的后台任务 - 这就是为什么 5 秒后您的歌曲将停止。
您可以使用Foreground service来解决这个问题:
A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.
您可以找到许多有关如何使用前台服务的示例,例如 Foreground Service Android Example或this thread
关于android - 如何让Android Pie中的后台服务继续运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57922145/