我希望我的应用程序可以在运行过程中播放音乐。我正在尝试使用“Service”实现它。这是“MyService.class”文件。
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
MediaPlayer mMediaPlayer = null;
private static final String ACTION_PLAY = "com.example.action.PLAY";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.theme_song);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
return 1;
} else {
return 0;
}
}
public void onPrepared(MediaPlayer player) {
player.start();
}
}
请问如何在我的活动(MyActivity)中使用 Service
,以及需要在 MyService.class 中定义哪些其他方法才能获得正确的结果。