You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 6后台音乐播放自动停止,亮屏才加载下一曲的技术问题

Hey there, let's break down this annoying Android 6 audio playback issue you're dealing with! It sounds like the core problem is tied to how your app handles track switching when the screen is off—super common with Marshmallow's stricter background restrictions. Here's how to diagnose and fix it:

1. First, Rule Out Doze Mode (Android 6's Big Culprit)

Android 6 introduced Doze Mode, which throttles CPU, network, and background activity when the screen is off for a while. This is almost certainly blocking your next-track loading logic.

  • Test it: Go to Developer Options → enable "Stay awake" (keep screen on) or run adb shell dumpsys deviceidle disable to turn off Doze temporarily. If the problem disappears, you've found your main issue.
  • Fix it: Register your app for ignore battery optimizations (ask users for permission) and make sure your playback service runs as a foreground service with a persistent notification—this keeps it exempt from Doze restrictions.
2. Check Your MediaSessionCompat Implementation

Since you used a background audio tutorial, double-check these critical points:

  • Ensure your MediaBrowserServiceCompat is properly bound to a active MediaSessionCompat, and you're handling onPlayFromMediaId (or custom next-track triggers) correctly. When the screen is off, the system relies on the media session to wake your service.
  • Confirm you're calling setActive(true) on your media session when playback starts—this tells the system your app is actively playing audio and shouldn't be suspended.
3. Fix Your Track Loading Threading

You mentioned using an ArrayList for song paths—if you're loading/parsing the next track on the main thread, that's a problem. Android 6 can suspend the main thread when the screen is off, blocking your load logic.

  • Fix it: Move all track loading (path resolution, metadata parsing, MediaPlayer preparation) to a background thread. Use AsyncTask, HandlerThread, or coroutines (if using Kotlin) to keep this work off the main thread.
  • Example snippet for background prep:
new AsyncTask<Void, Void, MediaPlayer>() {
    @Override
    protected MediaPlayer doInBackground(Void... voids) {
        MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(nextTrackPath);
            mp.prepare();
        } catch (IOException e) {
            Log.e("Player", "Failed to load track", e);
        }
        return mp;
    }

    @Override
    protected void onPostExecute(MediaPlayer mediaPlayer) {
        // Switch to the new player and start playback
        mediaPlayer.start();
    }
}.execute();
4. Use a WakeLock (Sparingly)

To prevent the system from putting the CPU to sleep during playback, you need a PARTIAL_WAKE_LOCK. Just remember to release it when playback stops/pauses to save battery.

  • Add this permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK" />
  • Implement the wake lock in your playback service:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyPlayer::AudioWakeLock");

// Acquire before playback starts
wakeLock.acquire();

// Release when playback stops/pauses
if (wakeLock.isHeld()) {
    wakeLock.release();
}
5. Add Error Logging to Catch Silent Failures

Sometimes track loading fails silently when the screen is off. Add an error listener to your MediaPlayer to log what's going wrong:

mediaPlayer.setOnErrorListener((mp, errorCode, extraCode) -> {
    Log.e("Player", "Playback error: Code " + errorCode + ", Extra " + extraCode);
    // Trigger next track retry here if needed
    return true;
});
Testing App Tweaks

To narrow down the issue further, add detailed logging to your test app:

  • Log timestamps when you trigger next track, start loading, and finish loading.
  • Log whether the screen is on/off when these events happen (use PowerManager.isInteractive() to check).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:10:16