安卓后台保活黑科技 播放无声音乐

栏目: Android · 发布时间: 6年前

内容简介:1、准备一段无声的音频,新建一个播放音乐的Service类,将播放模式改为无限循环播放。在其onDestroy方法中对自己重新启动。2、 在保活的DownloadServie服务类的onCreate方法中对PlayerMusicService进行启动3、在Manifest文件中进行注册

1、准备一段无声的音频,新建一个播放音乐的Service类,将播放模式改为无限循环播放。在其onDestroy方法中对自己重新启动。

public class PlayerMusicService extends Service {    private final static String TAG = PlayerMusicService.class.getSimpleName();    private MediaPlayer mMediaPlayer;    @Nullable
    @Override
    public IBinder onBind(Intent intent) {        return null;
    }    @Override
    public void onCreate() {        super.onCreate();
        Logger.d(TAG, TAG + "---->onCreate,启动服务");
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silent);
        mMediaPlayer.setLooping(true);
    }    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {        new Thread(new Runnable() {            @Override
            public void run() {
                startPlayMusic();
            }
        }).start();        return START_STICKY;
    }    private void startPlayMusic() {        if (mMediaPlayer != null) {
            Logger.d(TAG, "启动后台播放音乐");
            mMediaPlayer.start();
        }
    }    private void stopPlayMusic() {        if (mMediaPlayer != null) {
            Logger.d(TAG, "关闭后台播放音乐");
            mMediaPlayer.stop();
        }
    }    @Override
    public void onDestroy() {        super.onDestroy();
        stopPlayMusic();
        Logger.d(TAG, TAG + "---->onCreate,停止服务");        // 重启自己
        Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
        startService(intent);
    }
}

2、 在保活的DownloadServie服务类的onCreate方法中对PlayerMusicService进行启动

 Intent intent = new Intent(this, PlayerMusicService.class);
 startService(intent);

3、在Manifest文件中进行注册

  <service
            android:name=".service.PlayerMusicService"
            android:enabled="true"
            android:exported="true"
            android:process=":music_service" />

以上所述就是小编给大家介绍的《安卓后台保活黑科技 播放无声音乐》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computers and Intractability

Computers and Intractability

M R Garey、D S Johnson / W. H. Freeman / 1979-4-26 / GBP 53.99

This book's introduction features a humorous story of a man with a line of people behind him, who explains to his boss, "I can't find an efficient algorithm, but neither can all these famous people." ......一起来看看 《Computers and Intractability》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具