目錄
- service
- 清單文件
- 啟動(dòng)服務(wù)
- 無聲音樂下載
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,啟動(dòng)服務(wù)");
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, "啟動(dòng)后臺(tái)播放音樂");
mMediaPlayer.start();
}
}
private void stopPlayMusic() {
if (mMediaPlayer != null) {
Log.d(TAG, "關(guān)閉后臺(tái)播放音樂");
mMediaPlayer.stop();
}
}
@Override
public void onDestroy() {
super.onDestroy();
stopPlayMusic();
Log.d(TAG, TAG + "---->onCreate,停止服務(wù)");
// 重啟
Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
startService(intent);
}
}
清單文件
<!-- 無聲音樂 -->
<service
android:name=".PlayerMusicService"
android:enabled="true"
android:exported="true"
android:process=":music_service" />
啟動(dòng)服務(wù)
startService(new Intent(this, PlayerMusicService.class));
好人做到底
無聲音樂下載