目录
- service
- 清单文件
- 启动服务
- 无声音乐下载
service
package com.cpsc.sanya.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import com.cpsc.sanya.R;
/**
* 描述:
* <p>
*
* @author allens
* @date 2018/1/24
*/
public class PlayerMusicService extends Service {
private final static String TAG = "PlayerMusicService";
private MediaPlayer mMediaPlayer;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, TAG + "---->onCreate,启动服务");
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.no_notice);
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) {
Log.d(TAG, "启动后台播放音乐");
mMediaPlayer.start();
}
}
private void stopPlayMusic() {
if (mMediaPlayer != null) {
Log.d(TAG, "关闭后台播放音乐");
mMediaPlayer.stop();
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopPlayMusic();
Log.d(TAG, TAG + "---->onCreate,停止服务");
// 重启
Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
startService(intent);
}
}
清单文件
<!-- 无声音乐 -->
<service
android:name=".PlayerMusicService"
android:enabled="true"
android:exported="true"
android:process=":music_service" />
启动服务
startService(new Intent(this, PlayerMusicService.class));
好人做到底
无声音乐下载
https://pan.baidu.com/s/1smPKs5f
作者:Allens_Jiang
链接:https://www.jianshu.com/p/6445dbe420f4
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。