Android-服务与广播接收者实现本地音乐播放

来源:互联网 发布:男友尺寸知乎 编辑:程序博客网 时间:2024/05/16 06:17

源码下载地址:http://download.csdn.net/detail/u014657752/9050473

效果图:



布局:

<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical"    tools:context=".MainActivity">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="play"        android:text="播放" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="stop"        android:text="暂停播放" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="continueplay"        android:text="继续播放" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="loop"        android:text="循环播放" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="back"        android:text="后台播放" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="exit"        android:text="退出" />    <SeekBar        android:id="@+id/sb"        android:layout_width="match_parent"        android:layout_height="wrap_content" /></LinearLayout></span></span>


interface.java
<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;">package com.example.yulongji.android11;/** * Created by yulongji on 2015/8/26. */public interface MusicInterface {    void play();    void stop();    void continueplay();    void loop();    void seekto(int progress);}</span></span>


MusicService.java
</pre><pre>
package com.example.yulongji.android11;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.Binder;import android.os.Bundle;import android.os.Environment;import android.os.IBinder;import android.os.Message;import java.io.IOException;import java.util.Timer;import java.util.TimerTask;public class MusicService extends Service {    private MediaPlayer Player;    private Timer timer;    private int duration;    private int currentPosition;    private boolean flag;    @Override    public IBinder onBind(Intent intent) {        //返回MusicController        return new MusicController();    }    public class MusicController extends Binder implements MusicInterface {        @Override        public void play() {            MusicService.this.play();        }        @Override        public void stop() {            MusicService.this.stop();        }        @Override        public void continueplay() {            MusicService.this.continueplay();        }        @Override        public void seekto(int progress) {            MusicService.this.seekto(progress);        }        @Override        public void loop() {            MusicService.this.loop();        }    }    @Override    public void onCreate() {        super.onCreate();        Player = new MediaPlayer();    }    @Override    public void onDestroy() {        super.onDestroy();        //停止播放        Player.stop();        //释放占用的资源,此时player对象已经废掉了        Player.release();        Player = null;        if(timer != null){            timer.cancel();            timer = null;        }    }    //服务中的播放    public void play() {        //重置        Player.reset();        //获取音频文件路径        String path = Environment.getExternalStorageDirectory() + "/" + "xhn.mp3";        //添加路径        try {            Player.setDataSource(path);//           Player.setDataSource("http://192.168.47.38:8080/mytest/xhn.mp3");//           Player.prepare();            Player.prepareAsync();            Player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {                @Override                public void onPrepared(MediaPlayer mp) {                    Player.start();                    addTimer();                }            });        } catch (IOException e) {            e.printStackTrace();        }    }    //服务中的暂停    public void stop() {        Player.pause();    }    //服务中的继续播放    public void continueplay() {        Player.start();    }    public void loop() {            Player.setLooping(true);    }    //拖动进度    public void seekto(int progress) {        Player.seekTo(progress);    }    //添加定时发送消息给handler时时改变seekbar的值    public void addTimer() {        if (timer == null) {            timer = new Timer();            timer.schedule(new TimerTask() {                @Override                public void run() {                    //获取歌曲总时长                    duration = Player.getDuration();                    //获取当前播放位置                    currentPosition = Player.getCurrentPosition();                    //把进度封装至消息对象中                    Message msg = MainActivity.handler.obtainMessage();                    //把进度封装至消息对象中                    Bundle bundle = new Bundle();                    bundle.putInt("duration", duration);                    bundle.putInt("currentPosition", currentPosition);                    msg.setData(bundle);                    MainActivity.handler.sendMessage(msg);                }                //开始计时任务后的5毫秒,第一次执行run方法,以后每500毫秒执行一次            }, 5, 500);        }    }}

MainActivity.java
<span style="font-family:KaiTi_GB2312;font-size:18px;"><span style="font-family:KaiTi_GB2312;font-size:18px;">package com.example.yulongji.android11;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.view.View;import android.widget.SeekBar;public class MainActivity extends Activity {    private MyServiceConn conn;    private Intent intent;    MusicInterface musinter;    private static SeekBar sb;    static Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            //获取message中的消息            Bundle bundle = msg.getData();            //从bundle中取出数据            int duration = bundle.getInt("duration");            int currentPosition = bundle.getInt("currentPosition");            //刷新进度条的进度            sb.setMax(duration);            sb.setProgress(currentPosition);        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        intent = new Intent(this, MusicService.class);        //先启动服务,再绑定服务        startService(intent);        conn = new MyServiceConn();        //绑定服务        bindService(intent, conn, BIND_AUTO_CREATE);        sb = (SeekBar) findViewById(R.id.sb);        //seekbar改变监听事件        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {            //停止拖动松手后进度值            @Override            public void onStopTrackingTouch(SeekBar seekBar) {                int progress = seekBar.getProgress();                //改变播放进度                musinter.seekto(progress);            }            //进度值正在改变            @Override            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {                //根据拖动的进度改变音乐播放进度            }            //拖动前开始进度值            @Override            public void onStartTrackingTouch(SeekBar seekBar) {            }        });    }    //绑定服务必须实现ServiceConnection接口    public class MyServiceConn implements ServiceConnection {        //连接成功后将返回的IBinder 对象传给MusicInterface        @Override        public void onServiceConnected(ComponentName name, IBinder service) {            musinter = (MusicInterface) service;        }        @Override        public void onServiceDisconnected(ComponentName name) {        }    }    //播放    public void play(View view) {        musinter.play();    }    //继续播放    public void continueplay(View view) {        musinter.continueplay();    }    //暂停播放    public void stop(View view) {        musinter.stop();    }    //后台播放    public void back(View view) {        finish();    }    public void loop(View view) {        musinter.loop();    }    //退出应用    public void exit(View view) {        //先解绑        unbindService(conn);        //后停止服务        stopService(intent);        finish();    }}</span></span>



0 0
原创粉丝点击