您的位置:首页 > 其它

使用服务实现简单的音乐播放

2015-10-14 20:16 666 查看
今天下午我们还使用服务实现了一个简单的音乐播放器。

步骤:

1、在res文件夹下创建raw文件夹,把我们要播放的音频文件放在raw文件夹下。

2、下面就是创建服务对象的子类了。

MainActivity:

package com.example.text03;

import com.example.text03.MyService.MyBinder;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

private MyServiceConnection conn;
private MyService myService;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, MyService.class);
conn = new MyServiceConnection();
}

public void play(View view){
myService.play();
}
public void continuePlay(View view){
myService.continuePlay();
}
public void pause(View view){
myService.pause();
}
public void bind(View view){
bindService(intent, conn, BIND_AUTO_CREATE);
}
public void unbind(View view){
unbindService(conn);
}
class MyServiceConnection implements ServiceConnection{

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyBinder binder = (MyBinder) service;
myService = binder.getMyService();
}

@Override
public void onServiceDisconnected(ComponentName name) {
}

}
}
继承自Service的字了MyService

package com.example.text03;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {

//声明一个媒体播放器
private MediaPlayer player;
//记录播放的位置
private int position;
@Override
public void onCreate() {

super.onCreate();
//初始化媒体播放器
if (player == null) {
//Uri uri = Uri.fromFile(file);
player = MediaPlayer.create(MyService.this, R.raw.eason);
//设置播放模式:单曲循环
player.setLooping(true);
}else{
//设置音乐播放完毕后的方法
player.setOnCompletionListener(new OnCompletionListener() {

@Override
public void onCompletion(MediaPlayer mp) {
//释放资源
player.release();
}
});
}
}
@Override
public IBinder onBind(Intent intent) {

return new MyBinder();
}
class MyBinder extends Binder{
public MyService getMyService(){
return MyService.this;
}
}
public void play(){
if (player != null && !player.isPlaying()) {
if (position == 0) {
try {
//从头播放,想调用start必须先调用stop
player.stop();
//准备方法
player.prepare();
//开始播放
player.start();
} catch (Exception e) {

e.printStackTrace();
}
}else{
//设置进度
player.seekTo(position);
player.start();
}
}
}
public void continuePlay(){
if (player != null && player.isPlaying()) {
//获取当前播放的位置
position = player.getCurrentPosition();
//暂停音乐
player.pause();
}
}
public void pause(){
if (player != null) {
//停止方法
player.stop();
//重置媒体播放器
player.reset();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: