android音乐播放器实现(Service+BroadcastReceiver+Notification)

public interface IMusic {  
    public void moveon();//继续  
    public void pause();//暂停  
    public void stop();//停止  
    public void nextSong();//下一曲  
    public void lastSong();//上一曲  
}  

定义Application类,用于传递全局变量:

public class Mp3Application extends Application {  
    public List songsList;//当前播放列表  
    public int songItemPos;//当前播放音乐在列表中的位置  
    public NotificationManager notManager;  
    public IMusic music;  
}  

定义Service类,用于控制音乐播放:
public class PlayerService extends Service {  
    private MediaPlayer mp;  
    private Mp3Application application;  
    private List songs;  
    private int songItemPos;  

    @Override  
    public void onCreate() {  
        super.onCreate();  
        application = (Mp3Application) getApplication();  
        songs = application.songsList;  
    }  

    @Override  
    public IBinder onBind(Intent intent) {  
        play(songItemPos);  
        return new MusicListener();  
    }  

    public void play(int position) {  
"white-space:pre">        //传入播放位置在列表中的边界  
        if(position>=0){  
            position=position % application.songsList.size();  
        }  
        else{  
            position = application.songsList.size()+ position;  
        }  

        application.songItemPos = position;//在全局变量中标记当前播放位置  
        Song currentSong = songs.get(position);//获取当前播放音乐  
        Uri musicTableForSD = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
        Uri uri = Uri.withAppendedPath(musicTableForSD,  
                "/" + currentSong.getId());//初始化mp对象  
        mp = MediaPlayer.create(this, uri);  

        System.out.println(currentSong.getName());  

        try {  
            mp.start();  

        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

    @Override  
    public boolean onUnbind(Intent intent) {  
        mp.stop();  
        mp.release();  
        mp = null;  
        return super.onUnbind(intent);  
    }  

    @Override  
    public void onDestroy() {  
        super.onDestroy();  
    }  
"white-space:pre">    //实现IMusic接口,用于接收播放信息  
    private class MusicListener extends Binder implements IMusic {  

        @Override  
        public void moveon() {  
            if (mp != null) {  
                mp.start();  
            }  
        }  

        @Override  
        public void pause() {  
            if (mp != null) {  
                mp.pause();  
            }  
        }  

        @Override  
        public void stop() {  
            if (mp != null) {  
                mp.stop();  
                mp.release();  
                mp = null;  
            }  
        }  

        @Override  
        public void nextSong() {  
            if (mp != null) {  
                mp.stop();  
                play(++application.songItemPos);  
            }  
        }  

        @Override  
        public void lastSong() {  
            if (mp != null) {  
                mp.stop();  
                play(--application.songItemPos);  
            }  
        }  
    }  

}  

初始化Notification,该部分主要在Activity中完成:
Notification的布局效果(即contentView):

public class MainActivity extends Activity {  
    .....  
    private RemoteViews contentView;  

    private Notification notification;  
    private Mp3Application application;  
    private IMusic music;  
    .....  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  

        ......         

        // 初始化通知栏播放控件  
        initNotificationBar();  

        ......  
    }  

    public void initNotificationBar() {  
        notification = new Notification();  
        //初始化通知  
        notification.icon = R.drawable.ic_launcher;  
        contentView = new RemoteViews(getPackageName(),  
                R.layout.notification_control);  
        notification.contentView = contentView;  

        Intent intentPlay = new Intent("play");//新建意图,并设置action标记为"play",用于接收广播时过滤意图信息  
        PendingIntent pIntentPlay = PendingIntent.getBroadcast(this, 0,  
                intentPlay, 0);  
        contentView.setOnClickPendingIntent(R.id.bt_notic_play, pIntentPlay);//为play控件注册事件  

        Intent intentPause = new Intent("pause");  
        PendingIntent pIntentPause = PendingIntent.getBroadcast(this, 0,  
                intentPause, 0);  
        contentView.setOnClickPendingIntent(R.id.bt_notic_pause, pIntentPause);  

        Intent intentNext = new Intent("next");  
        PendingIntent pIntentNext = PendingIntent.getBroadcast(this, 0,  
                intentNext, 0);  
        contentView.setOnClickPendingIntent(R.id.bt_notic_next, pIntentNext);  

        Intent intentLast = new Intent("last");  
        PendingIntent pIntentLast = PendingIntent.getBroadcast(this, 0,  
                intentLast, 0);  
        contentView.setOnClickPendingIntent(R.id.bt_notic_last, pIntentLast);  

        Intent intentCancel = new Intent("cancel");  
        PendingIntent pIntentCancel = PendingIntent.getBroadcast(this, 0,  
                intentCancel, 0);  
        contentView  
                .setOnClickPendingIntent(R.id.bt_notic_cancel, pIntentCancel);  
        notification.flags = notification.FLAG_NO_CLEAR;//设置通知点击或滑动时不被清除  
        application.notManager.notify(Const.NOTI_CTRL_ID, notification);//开启通知  

    }  

}  
定义BroadcastReceiver类,用于接收来自Notification的广播并控制音乐播放:

public class Mp3Receiver extends BroadcastReceiver {  
    private Mp3Application application;  
    private IMusic music;  

    @Override  
    public void onReceive(Context context, Intent intent) {  

        application = (Mp3Application) context.getApplicationContext();  
        String ctrl_code = intent.getAction();//获取action标记,用户区分点击事件  

        music = application.music;//获取全局播放控制对象,该对象已在Activity中初始化  
        if (music != null) {  
            if ("play".equals(ctrl_code)) {  
                music.moveon();  
                System.out.println("play");  
            } else if ("pause".equals(ctrl_code)) {  
                music.pause();  
                System.out.println("pause");  
            } else if ("next".equals(ctrl_code)) {  
                music.nextSong();  
                System.out.println("next");  
            } else if ("last".equals(ctrl_code)) {  
                music.lastSong();  
                System.out.println("last");  
            }  
        }  

        if ("cancel".equals(ctrl_code)) {  
            application.notManager.cancel(Const.NOTI_CTRL_ID);  
            System.exit(0);  
        }  
    }  

}  


最后别忘了在清单文件中声明广播类并定制广播哦:
"com.cxc.Mp3Player.util.Mp3Application"  
    android:allowBackup="true"  
    android:icon="@drawable/ic_launcher"  
    android:label="@string/app_name"  
    android:theme="@style/AppTheme" >  
    "android.test.runner" >  
      

    ......  

    "com.cxc.Mp3Player.receiver.Mp3Receiver"  
        android:exported="true" >  
          
            "play" />  
            "last" />  
            "next" />  
            "pause" />  
            "cancel" />  
          
      
  

你可能感兴趣的:(音乐播放器)