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<Song> songsList;//當前播放列表  
    public int songItemPos;//當前播放音樂在列表中的位置  
    public NotificationManager notManager;  
    public IMusic music;  
}  

定義Service類,用於控制音樂播放:
public class PlayerService extends Service {  
    private MediaPlayer mp;  
    private Mp3Application application;  
    private List<Song> 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) {  
<span style="white-space:pre">        </span>//傳入播放位置在列表中的邊界  
        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();  
    }  
<span style="white-space:pre">    </span>//實現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);  
        }  
    }  

}  


最後別忘了在清單文件中聲明廣播類並定製廣播哦:
<application  
    android:name="com.cxc.Mp3Player.util.Mp3Application"  
    android:allowBackup="true"  
    android:icon="@drawable/ic_launcher"  
    android:label="@string/app_name"  
    android:theme="@style/AppTheme" >  
    <uses-library android:name="android.test.runner" >  
    </uses-library>  

    ......  

    <receiver  
        android:name="com.cxc.Mp3Player.receiver.Mp3Receiver"  
        android:exported="true" >  
        <intent-filter>  
            <action android:name="play" /><!-- 定製play廣播 -->  
            <action android:name="last" /><!-- 定製last廣播 -->  
            <action android:name="next" /><!-- ...... -->  
            <action android:name="pause" />  
            <action android:name="cancel" />  
        </intent-filter>  
    </receiver>  
</application>  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章