AndroidMediaplayer在前台服务中播放2分钟后停止
创始人
2024-10-09 02:01:27
0
  1. 使用WakeLock

在播放媒体文件的时候,需要保证设备不会锁屏或者进入休眠状态。可以使用WakeLock来实现:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();

使用完MediaPlayer后释放WakeLock:

if (mp != null) {
    mp.release();
    mp = null;
}

if (wl != null) {
    wl.release();
    wl = null;
}
  1. 使用startForeground方法

在服务中使用startForeground方法可以将服务设置为前台服务,这样系统就不会轻易地停止服务了。

private void startForeground() {
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("Foreground Service")
            .setContentText("Media Player is running")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(1, notification);
}

然后在播放媒体文件的时候,调用此方法:

private void startMediaPlayer() {
    if (mp != null) {
        mp.release();
        mp = null;
    }

    mp = new MediaPlayer();
    mp.setDataSource("http://example.com/song.mp3");
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.start();
            startForeground();
        }
    });
    mp.prepareAsync();
}

这样,就可以解决MediaPlayer在前台服务中播放2分钟后停止的问题了。

相关内容

热门资讯

透视脚本!wepoker私人局... 透视脚本!wepoker私人局辅助挂,wpk透视辅助,操作教程(一直真的是有挂)-哔哩哔哩1、wep...
透视脚本!德普软件,wepok... 透视脚本!德普软件,wepoker有辅助功能吗,经验教程(其实真的有挂)-哔哩哔哩该软件可以轻松地帮...
透视规律!wpk控制牌是真的吗... 透视规律!wpk控制牌是真的吗,wpk有辅助吗,资料教程(切实是真的挂)-哔哩哔哩1)wpk控制牌是...
透视总结!约局吧德州真的有透视... 透视总结!约局吧德州真的有透视挂吗,wepoker私人定制透视,模板教程(本来是有挂)-哔哩哔哩1、...
透视辅助!poker worl... 透视辅助!poker world辅助器,wepoker底牌透视,阶段教程(一贯存在有挂)-哔哩哔哩透...
透视讲解!hhpoker辅助挂... 透视讲解!hhpoker辅助挂是真的吗,智星德州辅助译码插件靠谱吗,练习教程(原来有挂)-哔哩哔哩1...
透视苹果版!佛手在线是不是有挂... 透视苹果版!佛手在线是不是有挂,aapoker免费透视脚本,学习教程(真是有挂)-哔哩哔哩1、很好的...
透视代打!wepoker辅助软... 透视代打!wepoker辅助软件视频,wepoker透视底牌,指南书教程(其实是有挂)-哔哩哔哩1、...
透视系统!红龙poker辅助工... 透视系统!红龙poker辅助工具,wepoker到底有没有透视,妙计教程(果然真的有挂)-哔哩哔哩w...
透视挂透视!wepoker辅助... 透视挂透视!wepoker辅助器是真的吗,哈糖大菠萝免费辅助器,妙招教程(总是真的有挂)-哔哩哔哩1...