5.22
音乐功能:
package com.example.yibaifen;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class MusicService extends Service {
private static final String TAG = "MusicService";
private MediaPlayer mediaPlayer;
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.background_music);
mediaPlayer.setLooping(true); // 设置循环播放
mediaPlayer.setVolume(1.0f, 1.0f); // 设置音量,范围是0.0f到1.0f
Log.d(TAG, "Service onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
Log.d(TAG, "Service onStartCommand: mediaPlayer.start()");
}
return START_STICKY;
}
@Override
public void onDestroy() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
Log.d(TAG, "Service onDestroy: mediaPlayer.stop()");
}
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class MusicService extends Service {
private static final String TAG = "MusicService";
private MediaPlayer mediaPlayer;
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.background_music);
mediaPlayer.setLooping(true); // 设置循环播放
mediaPlayer.setVolume(1.0f, 1.0f); // 设置音量,范围是0.0f到1.0f
Log.d(TAG, "Service onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
Log.d(TAG, "Service onStartCommand: mediaPlayer.start()");
}
return START_STICKY;
}
@Override
public void onDestroy() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
Log.d(TAG, "Service onDestroy: mediaPlayer.stop()");
}
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}