android - 如何让Android Pie中的后台服务继续运行?

标签 android

当应用程序从 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 LimitsBackground 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 Examplethis thread

关于android - 如何让Android Pie中的后台服务继续运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57922145/

相关文章:

java - 每次单击链接时 web View 中的进度对话框

java - 在 Edittext 中保存输入用户

java - Android 偏好设置 如何进行信息偏好设置

Android 编译不同资源(白标)

android - 如何将 Guava 库的**某些**部分导入Android应用程序(gradle)

java - 无法解决方法占位符 fragment 错误

android - <unknown> detectAndCompute() 中发生错误

java - AdMob 横幅出现在大屏幕 Android 设备屏幕中央

android - 如何开发一个分离数据层和 View 层的Android应用程序

android - 无法覆盖 onBackPressed 和 onKeyDown - Android