You need to enable JavaScript to run this app. Android音乐播放器后台Service1.5分钟停止及暂停功能实现咨询
优惠活动
大模型
产品
解决方案
定价
更多

Android音乐播放器后台Service1.5分钟停止及暂停功能实现咨询

问题修复方案

一、后台播放停止问题修复

问题原因

锁屏后播放1.5分钟停止,日志输出Inactivity, disconnecting from Service,核心原因是Android 8.0及以上系统对普通后台服务做了运行限制,无用户感知的后台服务在锁屏后一段时间会被系统主动回收,START_STICKY配置无法规避该限制。

修复步骤

  1. 新增必要权限
    在Manifest文件的<manifest>节点下新增以下权限:
<!-- 唤醒锁权限,防止CPU休眠导致播放中断 -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- 前台服务基础权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- Android 12+ 媒体类前台服务专属权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
  1. 改造Service为前台服务
    音乐播放属于用户可感知的核心功能,需要将服务升级为前台服务,同时在通知栏展示播放状态,避免被系统回收。修改后的BackgroundSoundService代码如下:
public class BackgroundSoundService extends Service {
    String song_string;
    int playPosition = 0;
    private static final String TAG = "BackgroundSoundService";
    MediaPlayer player;
    // 前台服务通知ID,不可为0
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "music_play_channel";

    public IBinder onBind(Intent arg0) {
        Log.i(TAG, "onBind()" );
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // Android 8.0+ 必须先创建通知渠道才能展示通知
        createNotificationChannel();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) return Service.START_STICKY;
        String action = intent.getStringExtra("action");

        // 处理暂停指令
        if ("ACTION_PAUSE".equals(action)) {
            if (player != null && player.isPlaying()) {
                playPosition = player.getCurrentPosition();
                player.pause();
                stopForeground(false);
            }
            return Service.START_STICKY;
        }

        // 处理继续播放指令
        if ("ACTION_PLAY".equals(action) && player != null) {
            player.seekTo(playPosition);
            player.start();
            startForeground(NOTIFICATION_ID, buildNotification());
            return Service.START_STICKY;
        }

        // 首次播放逻辑
        song_string= intent.getStringExtra("uri");
        if (song_string != null && player == null) {
            System.out.println("Song string : " + song_string);
            player = MediaPlayer.create(this, Uri.parse(song_string));
            // 绑定唤醒锁,防止锁屏后CPU休眠
            player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
            player.setLooping(false);
            player.setVolume(0.5f, 0.5f);
            if (playPosition > 0) {
                player.seekTo(playPosition);
            }
            player.start();
            // 启动前台服务
            startForeground(NOTIFICATION_ID, buildNotification());
        }
        return Service.START_STICKY;
    }

    // 创建通知渠道
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "音乐播放",
                    NotificationManager.IMPORTANCE_LOW);
            channel.setDescription("用于展示音乐播放状态");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    // 构建播放状态通知
    private Notification buildNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("正在播放")
                .setContentText("音乐播放中")
                .setSmallIcon(R.drawable.ic_play) // 替换为项目内的图标资源
                .setContentIntent(pendingIntent)
                .build();
    }

    @Override
    public void onDestroy() {
        if(player!=null) {
            player.stop();
            player.reset();
            player.release();
            Log.i(TAG, "service stopped...");
        }
        stopForeground(true);
        super.onDestroy();
    }

    // 原有其他生命周期方法保留即可
}

二、暂停功能实现

通过给Service发送带不同action标记的Intent实现播放/暂停控制,修改PlayerFragment中播放按钮的点击逻辑:

main_btn.setOnClickListener(v -> {
    if( main_btn.getDrawable().getConstantState().equals( main_btn.getContext().getDrawable(R.drawable.ic_play).getConstantState())) {
        // 播放逻辑
        new Thread(() -> {
            if (localSong == null) return;
            myService.putExtra("uri",localSong.toString());
            myService.putExtra("action", "ACTION_PLAY");
            mainActivity.startService(myService);
            // UI修改必须在主线程执行
            getActivity().runOnUiThread(()-> main_btn.setImageResource(R.drawable.ic_pause));
        }).start();
    } else {
        // 暂停逻辑
        new Thread(() -> {
            myService.putExtra("action", "ACTION_PAUSE");
            mainActivity.startService(myService);
            getActivity().runOnUiThread(()-> main_btn.setImageResource(R.drawable.ic_play));
        }).start();
    }
});

内容的提问来源于stack exchange,提问作者fariji1294

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 15:54:06