Android保活之循环播放无声音乐
基本思想
1,循环播放无声的音乐
2,在其它音乐占用时,合理的控制音乐的再次播放
实现效果
目前测试在华为机器上,一键清理不会杀死。
在三星Galaxy Note4上,
该方法+前台服务达到播放器的效果,一键清理不会清理
代码实现
主代码
public class MusicService extends Service {
private final String TAG = "MusicService";
private MediaPlayer mMediaPlayer;
private AudioManager mAudioManager;
private AudioManager.OnAudioFocusChangeListener mAudioFocusChange = new
AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Log.e(TAG, "AUDIOFOCUS_GAIN");
try {
startPlayMusic();
} catch (Exception e) {
e.printStackTrace();
}
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.e(TAG, "AUDIOFOCUS_LOSS");
mAudioManager.abandonAudioFocus(mAudioFocusChange);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.e(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.e(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
break;
}
}
};
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//音标处理
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
if (mAudioManager != null)
mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.no_notice);
mMediaPlayer.setLooping(true);
startPlayMusic();
return START_STICKY;
}
private void startPlayMusic() {
if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
Log.e(TAG, "启动后台播放音乐");
mMediaPlayer.start();
}
}
private void stopPlayMusic() {
if (mMediaPlayer != null) {
Log.e(TAG, "关闭后台播放音乐");
mMediaPlayer.stop();
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopPlayMusic();
Log.e(TAG, TAG + "---->onDestroy,停止服务");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
配置文件
<service
android:name=".MusicService"
android:enabled="true"
android:exported="true"/>
1
2
3
4
启动该服务
startService(new Intent(context, MusicService.class));
1
2
好人做到底,附上无声音乐的下载地址
点我下载,没有积分的联系微信公众号“Android唐浮”
联系
遇到问题或想持续学习,请关注公众号“Android唐浮”
————————————————
版权声明:本文为CSDN博主「Android唐浮」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011368551/article/details/91666120