【Android】简易音乐播放器 介绍使用Service和Broadcast播放音乐文件

               

使用service播放sdcard中的一首歌曲,并在service中通过广播broadcast通知Activity更新界面。下面三个最终的图分别是:初始化时,播放时,暂停时。

    

界面是两个按钮,采用LinearLayout布局。代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><Button    android:id="@+id/btnPlayOrPause"      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="播放"    android:layout_weight="1"    android:onClick="clickHandle"    /><Button    android:id="@+id/btnStop"      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="停止"    android:layout_weight="1"    android:onClick="clickHandle"    /></LinearLayout> 

1.主Activity中,有四部分:onCreate()方法、onDestroy()方法、BroadcastReceiver的一个类updateUIReceiver、和按钮事件处理方法clickHandl()。

扫描二维码关注公众号,回复: 6038829 查看本文章

在onCreate()方法中主要是注册一个广播。注意在onCreate()里注册,记得在onDestroy()方法里解除注册。

 @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                btnStartOrPause = (Button) findViewById(R.id.btnPlayOrPause);        btnStop = (Button) findViewById(R.id.btnStop);                //onCreate()里注册BroadcastReceiver        //onDestroy()里解除注册        //下面的"giuz.receiver.music"要在manifest.xml里注册          IntentFilter filter = new IntentFilter("giuz.receiver.music");        registerReceiver(updatUIReceiver, filter);            } 

在onDestroy()方法里解除注册,不然退出时会报异常。

@Override    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(updatUIReceiver);    } 

这里的广播类是在Activity里面定义的(也可以作为一个单独的类来写)。

//定义一个BroadcastReceiver    private BroadcastReceiver updatUIReceiver = new BroadcastReceiver() {        //当service发出广播后,此方法就可以得到service传回来的值        @Override        public void onReceive(Context context, Intent intent) {            //更新界面。这里改变Button的值            //得到intent返回来的值,0表示此时是播放,1表示暂停, 2是停止            int backFlag = intent.getExtras().getInt("backFlag");            switch(backFlag){            case 0:                btnStartOrPause.setText("暂停");                break;            case 1:            case 2:                btnStartOrPause.setText("播放");                break;            }        }    }; 

按钮处理事件

//处理按钮事件    public void clickHandle(View v){        switch(v.getId()){        case R.id.btnPlayOrPause:            intent = new Intent(AudioActi.this, giuz.service.MyAudioService.class);            Bundle bundle2service = new Bundle();            bundle2service.putString("audioPath", AUDIO_PATH);//前面要定义AUDIO_PATH            //BC_RECEIVER也要在前面定义,并在manifest.xml里注册            bundle2service.putString("bc_receiver", BC_RECEIVER);            intent.putExtras(bundle2service);            startService(intent);//开启服务            break;        case R.id.btnStop:            if(intent != null){                stopService(intent);//停止服务            }            break;        }    } 

2.在Service里,主要有onStart()、onDestroy()和sendBC4UpdateUI()几个方法。

先定义好下面这些对象

private MediaPlayer mediaPlayer = null;private Intent intent2bc = null;private Bundle bundle2bc = null;private String audioPath = null;private String bc_receiver = null; 

在onStart()方法中,通过用mediaPlayer.isPlaying()方法来判断当前音乐是在播放还是暂停,并利用广播传递相应的值给Activity用以更新界面。

@Override    public void onStart(Intent intent, int startId) {        super.onStart(intent, startId);        audioPath = intent.getExtras().getString("audioPath");        bc_receiver = intent.getExtras().getString("bc_receiver");        //1.正在播放        //使其暂停播放,并通知界面将Button的值改为"播放"(如果正在播放,Button值是"暂停")        if(mediaPlayer != null && mediaPlayer.isPlaying()){            mediaPlayer.pause();            sendBC4UpdateUI(1);//更新界面        }        //2.正在暂停        else{            if(mediaPlayer == null){                mediaPlayer = new MediaPlayer();//如果被停止了,则为null                try {                    mediaPlayer.setDataSource(audioPath);//设置播放的文件的路径                    mediaPlayer.prepare();                } catch (IllegalArgumentException e) {                    e.printStackTrace();                } catch (IllegalStateException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }            }                        mediaPlayer.start();            sendBC4UpdateUI(0);//更新界面                    }            } 

在onDestroy()方法中,要release掉mediaPlayer。

@Override    public void onDestroy() {        if(mediaPlayer !=null){            mediaPlayer.release();//停止时要release            sendBC4UpdateUI(2);//更新界面        }        super.onDestroy();    } 

而在sendBC4UpdateUI()方法里,就是发送广播了。

private void sendBC4UpdateUI(int flag) {        intent2bc = new Intent(bc_receiver);//bc_receiver前面已有定义,是从Activity传过来的        //如果缺少下面这句,关掉再重新打开播放器里点“停止”并不能停掉        intent2bc.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        bundle2bc = new Bundle();        bundle2bc.putInt("backFlag", flag);//把flag传回去        intent2bc.putExtras(bundle2bc);        sendBroadcast(intent2bc);//发送广播      //发送后,在Activity里的updateUIReceiver的onReceiver()方法里就能做相应的更新界面的工作了    } 

3.最后,manifest.xml注册如下。

<?xml version="1.0" encoding="utf-8"?>....    <application android:icon="@drawable/icon" android:label="@string/app_name">        <service android:name="giuz.service.MyAudioService"></service>        <activity....        </activity>    </application>    <uses-sdk android:minSdkVersion="8" /></manifest>  

以后可以通过改进做成一个mp3播放器。

转自: http://www.cnblogs.com/giuz/archive/2010/10/31/1865470.html

           

猜你喜欢

转载自blog.csdn.net/qq_44912644/article/details/89513108
今日推荐