如何保持媒体播放器服务 运行 直到它被终止?

How do I keep media player service running until it's killed?

我有一个媒体播放器服务,每当用户清除最近使用的应用程序时,该服务就会被终止。我希望服务继续在后台播放。我试过了

@Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        return START_STICKY;
    }

mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);

但它不起作用。我该如何解决这个问题?

如 Mr.Patel 答案中所述,

当前端 Activity 未 运行 或从最近的列表中删除时,许多制造商不允许 运行 后台服务。

有一种方法可以满足您的要求。

您可以 运行 通过在您的应用程序中设置不可取消的通知,您的服务会在后台运行。在您使用关闭按钮以编程方式强制关闭通知之前,您的服务将在后台 运行ning。

希望这能解决您的问题。

Google 做了一些更新:

其中一些更新包括安全性,并且它到达了服务。这意味着我们不能再在不通知用户的情况下在后台执行冗长的操作。

Foreground 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.

Background A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service. Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn't in the foreground. In most cases like this, your app should use a scheduled job instead.

确保尽快调用 startForeground

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String input = intent.getStringExtra("inputExtra");
    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Foreground Service")
            .setContentText(input)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);

    //do heavy work on a background thread


    //stopSelf();

    return START_STICKY;
}

这是启动前台服务的方式:

 public void startService() {
    Intent serviceIntent = new Intent(this, ForegroundService.class);
    serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");

    ContextCompat.startForegroundService(this, serviceIntent);
}