開(kāi)發(fā)一個(gè)簡(jiǎn)易安卓音樂(lè)播放器

本人初學(xué)Android,最近做了一個(gè)實(shí)現(xiàn)安卓簡(jiǎn)單音樂(lè)播放功能的播放器,收獲不少,于是便記錄下來(lái)自己的思路與知識(shí)總結(jié),重溫自己的探索之路。

1 ?那么先上幾張截圖來(lái)看下程序?qū)崿F(xiàn)效果吧

2 可以看出基本實(shí)現(xiàn)的功能有

暫停(播放),上(下)一首,停止播放

點(diǎn)擊列表中歌曲進(jìn)行播放,點(diǎn)擊按鈕以彈出歌曲列表

屏幕上顯示歌曲名稱(chēng),演唱者,專(zhuān)輯圖片

顯示播放進(jìn)度條,拖拽進(jìn)度條以控制播放

通知欄中顯示相關(guān)信息,并可在通知欄上控制播放


3 總體開(kāi)發(fā)思路

一共有兩個(gè)Activity界面(分別是主界面和播放細(xì)節(jié)界面),一個(gè)用以在后臺(tái)播放音樂(lè)的Service,一個(gè)可以和用戶(hù)進(jìn)行交互Notificatication。為了能夠使得活動(dòng)與活動(dòng),活動(dòng)與服務(wù),活動(dòng)與通知之間通信,采取發(fā)送廣播的做法,由于我在MainActivity,PlayActivity,MusicService中都獲取了歌曲信息列表,所以在他們之間直接傳遞歌曲下標(biāo)location和狀態(tài)isPlaying即可

核心是由MainActivity通過(guò)startService方法控制Service來(lái)進(jìn)行播放

MainActivity中點(diǎn)擊事件發(fā)生后更新自己的UI,同時(shí)startService

PlayActivity中點(diǎn)擊事件發(fā)生后更新自己UI,發(fā)送廣播給MainActivity,讓MainActivity更新UI,startService,從而實(shí)現(xiàn)PlayActivity間接控制播放

Notification點(diǎn)擊事件發(fā)生后發(fā)生廣播給MainActivity,讓MainActivity更新UI,startService,從而實(shí)現(xiàn)Notification間接控制播放


4 重要功能實(shí)現(xiàn)

1 ?內(nèi)容提供器 ContentProvider

內(nèi)容提供器用法一般有兩種: 使用現(xiàn)有的內(nèi)容提供器和創(chuàng)建自己的內(nèi)容提供器。

在使用系統(tǒng)自帶的內(nèi)容提供器,注意要在AndroidManifest中添加權(quán)限聲明,如果是危險(xiǎn)權(quán)限,還要進(jìn)行運(yùn)行時(shí)權(quán)限聲明,這里由于本人手機(jī)低于Android6.0系統(tǒng),顧沒(méi)有進(jìn)行運(yùn)行時(shí)申請(qǐng)。

這里我們使用了安卓自帶媒體庫(kù)所提供的接口來(lái)訪問(wèn)數(shù)據(jù)。詳情看2

2 ?安卓MediaStore

安卓為我們提供了自帶的媒體庫(kù),我們可以直接從中訪問(wèn)到所需的數(shù)據(jù)。這個(gè)MediaStore包括了多媒體數(shù)據(jù)庫(kù)的所有信息,包括音頻,視頻和圖像,android把所有的多媒體數(shù)據(jù)庫(kù)接口進(jìn)行了封裝,所有的數(shù)據(jù)庫(kù)不用自己進(jìn)行創(chuàng)建,直接調(diào)用利用ContentResolver去掉用那些封裝好的接口就可以進(jìn)行數(shù)據(jù)庫(kù)的操作了,實(shí)例如下:

1 通過(guò)genContentResolver的查詢(xún)方法獲得存儲(chǔ)有數(shù)據(jù)的Cursor對(duì)象

Cursor ?cursor=context.getContentResolver()

.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null)

//query方法第一個(gè)參數(shù)為 Uri:這個(gè)Uri代表要查詢(xún)的數(shù)據(jù)庫(kù)名稱(chēng)加上表的名稱(chēng),這里我們獲取所有的歌曲信息,后面四個(gè)參數(shù)為查詢(xún)條件和數(shù)據(jù)排列條件,這里我們都使用null

2獲得了數(shù)據(jù)結(jié)果Cursor對(duì)象后,我們讀取數(shù)據(jù)到程序的思路是:通過(guò)移動(dòng)光標(biāo)的位置來(lái)遍歷cursor的

每一行,然后根據(jù)所需提取每一行相應(yīng)列的信息,并添加到程序的變量中

for(int i=0;i

mp3InfoList.add(mp3Info);

3 ?界面編程

1 SeekBar的實(shí)現(xiàn)注意聲明android:thumb="@drawable/media_player_progress_button"http://滑動(dòng)的光標(biāo)

2 按鈕ImageButton背景聲明我采用如下:app:srcCompat="@drawable/play"/>

這樣在活動(dòng)中便可通過(guò)button.setDateResource(R.drawable....)來(lái)實(shí)現(xiàn)背景的切換,如果界面編程中直接使用setBackground方法,到時(shí)候會(huì)造成按鈕背景的重疊而 ? ? ? ? ?不是切 換的效果(親測(cè))

3 使用ListIView的時(shí)候注意要在活動(dòng)中setAdapter(),并設(shè)置響應(yīng)子項(xiàng)點(diǎn)擊事件(通過(guò)開(kāi)啟服務(wù)來(lái)播放點(diǎn)擊的那首音樂(lè))

5 Activity

1 點(diǎn)擊專(zhuān)輯圖片時(shí)使用startActivity方法由MainActivity進(jìn)入PlayActivity,并由intent傳遞相關(guān)信息

Intent intent=new Intent(MainActivity.this,PlayActivity.class);

intent.putExtra("state",isPlaying);

intent.putExtra("location",location);

startActivity(intent);

2 使用startService方法開(kāi)啟服務(wù),通過(guò)intent傳遞相關(guān)信息(case 0:播放所傳遞的location下標(biāo)那首歌

case 1 :暫停/播放 ? ? case 2:seekBar拖動(dòng)播放 ? ? case 3: 停止播放)

//傳遞歌曲下標(biāo)location并啟動(dòng)服務(wù)

Intent intent=new Intent(MainActivity.this,MusicService.class);

intent.putExtra("tag",0);

intent.putExtra("location",location);

startService(intent);

6 ?實(shí)現(xiàn)后臺(tái)自動(dòng)播放下一首音樂(lè) :只需為MediaPlayer對(duì)象設(shè)置setOnCompletionListener()方法即可,在方法中使歌曲下標(biāo)+1,播放即可,自動(dòng)播放下一首后記得發(fā)送廣播給

活動(dòng)和Notification以更新UI

//設(shè)置自動(dòng)播放下一首

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

@Override

public void onCompletion(MediaPlayer mediaPlayer) {

if(mediaPlayer!=null){

try {

if (++location < mp3InfoList.size()) {

mediaPlayer.reset();

mediaPlayer.setDataSource(MusicService.this, Uri.parse(mp3InfoList.get(location).getUrl()));

mediaPlayer.prepare();

mediaPlayer.start();

}

}catch (Exception e){

e.printStackTrace();

}

}

7 實(shí)現(xiàn)顯示播放進(jìn)度功能:在Service中創(chuàng)建一個(gè)繼承于AsyncTask的類(lèi),在該類(lèi)子線程中線程每0.5秒發(fā)送一次帶有當(dāng)前播放進(jìn)度的broadcast給活動(dòng)界面以更新UI

public Integer doInBackground(Void...parms){

//設(shè)置while (true)以達(dá)到循環(huán)不斷的目的

while (true){

try{

Thread.sleep(500);//線程沉睡500毫秒

}

catch (Exception e){

e.printStackTrace();

}

position=mediaPlayer.getCurrentPosition();//獲得mediaPlayer當(dāng)前播放進(jìn)度

if(position

Intent mIntent=new Intent("com.example.musicplayer.update_seekbar");

mIntent.putExtra("position",position);

sendBroadcast(mIntent);//發(fā)送廣播

}else{

break;

}

}

return 0;

}

8

為SeekBar設(shè)置點(diǎn)擊拖動(dòng)事件,通知seetOnSeekBarChangeListener(...)方法,其中OnSeekBarChangeListener類(lèi)對(duì)象需重寫(xiě)三個(gè)方法,在?public voidonStop TrackingTouch(SeekBar seekBar)方法中發(fā)送廣播給Service(帶有Progress信息)

在Service中接收progress信息調(diào)用MediaPlayer.seekTo(progress)方法來(lái)響應(yīng)拖動(dòng)事件

//為SeekBar設(shè)置點(diǎn)擊拖動(dòng)事件

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

@Override

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

}

@Override

public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override

public void onStopTrackingTouch(SeekBar seekBar) {

int progress=seekBar.getProgress();

Intent intent=new Intent(MainActivity.this, MusicService.class);

intent.putExtra("tag",2);

intent.putExtra("progress",progress);

startService(intent);

}

});

9

使用帶有布局的通知 : 與使用普通通知無(wú)異,但給通知使用setContent(RemoteViews remoteViews)方法來(lái)設(shè)定布局,remoteViews的點(diǎn)擊事件的響應(yīng)為向MainActivity發(fā)送廣播

remoteViews = new RemoteViews(getPackageName(), R.layout.remoteviews_item_dl);//設(shè)置RemoteViews的布局? ? ? ? ? ? remoteViews.setTextViewText(R.id.tv_filename, getPackageName());? // 設(shè)置標(biāo)題? ? ? ? ? ? remoteViews.setTextViewText(R.id.tv_content, "this is notification");? // 設(shè)置內(nèi)容

remoteViews.setImageViewBitmap(R.id.notification_imageView,bitmap);//設(shè)置控件Bitmap

remoteViews.setOnClickPendingIntent(R.id.notification_next,PendingIntent.getBroadcast(this,0,

new Intent("com.example.musicplayer.notification.next").putExtra("tag2",2), PendingIntent.FLAG_UPDATE_CURRENT));// 設(shè)置點(diǎn)擊事件響應(yīng)結(jié)果為發(fā)送廣播

Notification notification=new NotificationCompat.builder(this).setContent(remotoViews).build();//構(gòu)建出帶有特定布局的通知

manager.notify(0,notification);//顯示通知

10

實(shí)現(xiàn)點(diǎn)擊按鈕彈出AlertIDialog,在dialog中顯示歌曲列表listView并設(shè)置點(diǎn)擊事件,關(guān)鍵在于為L(zhǎng)istView控件設(shè)置適配器:這里使用SimpleAdapter創(chuàng)建(要求綁定的數(shù)據(jù)是List>數(shù)據(jù)類(lèi)型(String為key,第二個(gè)參數(shù)為對(duì)應(yīng)數(shù)據(jù)))獲得dialog框架布局LinearoutLayout和歌曲列表布局ListView,并將ListIView添加到框架布局上

建立一個(gè)數(shù)組存儲(chǔ)listview上顯示的數(shù)據(jù)

獲取到集合數(shù)據(jù)

創(chuàng)建SimpleAdapter實(shí)例,參數(shù)解讀(context,數(shù)據(jù)數(shù)組,listVIew item的布局,key數(shù)組,布局id數(shù)組),將key儲(chǔ)存的數(shù)據(jù)賦予布局中相應(yīng)id控件

為listView設(shè)置Adapter

dialog.setView(dialog 框架布局),dialog.show()

listView設(shè)置點(diǎn)擊事件(發(fā)送帶有點(diǎn)擊item下標(biāo)信息的廣播給MainActivity)

//通過(guò)AlertDialog顯示歌曲列表

public void showMusicList(){

Log.d("PlayActivity","showMusicList start");

LinearLayout linearLayoutMain = new LinearLayout(this);//自定義一個(gè)布局文件

linearLayoutMain.setLayoutParams(new LinearLayout.LayoutParams(

LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

Log.d("PlayActivity","LinearLayout created");

ListView listView = new ListView(this);//this為獲取當(dāng)前的上下文

listView.setFadingEdgeLength(0);

List>musicList=new ArrayList>();

for(int i=0;i

Mapitem=new HashMap();

item.put("musicName",mp3InfoList.get(i).getTitle().toString());

item.put("artist",mp3InfoList.get(i).getArtist().toString());

musicList.add(item);

}

Log.d("PlayActivity","LinearLayout created and itialized");

//

SimpleAdapter adapter=new SimpleAdapter(PlayActivity.this,musicList,R.layout.music_item

,new String[]{"musicName","artist"}

, new int[]{R.id.music_item_musicName,R.id.music_item_artist});

Log.d("PlayActivity","SimpleAdapter created");

listView.setAdapter(adapter);

linearLayoutMain.addView(listView);

Log.d("PlayActivity","listView was added to the linearLayout");

final AlertDialog dialog=new AlertDialog.Builder(this).setTitle("歌曲列表").setView(linearLayoutMain)

.setNegativeButton("取消", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

dialog.cancel();

}

}).create();

Log.d("PlayActivity","Dialog created");

dialog.show();

Log.d("PlayActivity","Dialog showed");

//響應(yīng)子項(xiàng)點(diǎn)擊事件

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

//? ? ? ? ? 注意這里的參數(shù)第三個(gè)參數(shù)Item在適配器中的位置public void onItemClick(AdapterView adapterView, View view, int i, long l) {? ? ? ? ? ? ? ? //更新自身UI? ? ? ? ? ? ? ? musicNameView.setText(mp3InfoList.get(i).getTitle());? ? ? ? ? ? ? ? artistView.setText(mp3InfoList.get(i).getArtist());? ? ? ? ? ? ? ? durationView.setText(MediaUtil.formatTime(mp3InfoList.get(i).getDuration()));? ? ? ? ? ? ? ? //發(fā)送廣播附帶歌曲下標(biāo)給MainActivity來(lái)控制服務(wù)播放歌曲? ? ? ? ? ? ? ? Intent intent=new Intent("com.example.musicplayer.react_to_playactiity");? ? ? ? ? ? ? ? intent.putExtra("tag1",4);? ? ? ? ? ? ? ? intent.putExtra("location",i);? ? ? ? ? ? ? ? sendBroadcast(intent);? ? ? ? ? ? ? ? Log.d("PlayActivity","broadcast sended");? ? ? ? ? ? ? ? dialog.cancel();? ? ? ? ? ? ? ? Log.d("PlayActivity","Dialog canceled");? ? ? ? ? ? }? ? ? ? });? ? }


5 開(kāi)發(fā)思路的實(shí)現(xiàn)細(xì)節(jié)

1 首先新建保存mp3音樂(lè)相關(guān)屬性信息的實(shí)體類(lèi)Mp3Info(保存url,title,artist等等)

ublic class Mp3Info {

private String url;//路徑

private String title;//歌曲名

private String artist;//藝術(shù)家

private long duration;//歌曲時(shí)長(zhǎng)

private long id;

private long albumId;//以上兩種Id用以獲取專(zhuān)輯圖片

public Mp3Info(){

}

public Mp3Info(String url,String title,String artist,long duration,long id,long albumId){

this.url=url;

this.title=title;

this.artist=artist;

this.duration=duration;

this.id=id;

this.albumId=albumId;

}

public void setUrl(String url){

this.url=url;

}

public void setTitle(String title){

this.title=title;

}

public void setArtist(String artist){

this.artist=artist;

}

public void setDuration(long duration){

this.duration=duration;

}

public void setId(long id){this.id=id;}

public void setAlbumId(long albumId){this.albumId=albumId;}

public String getUrl(){

return url;

}

public String getTitle(){

return title;

}

public String getArtist(){

return artist;

}

public long getDuration(){

return duration;}

public long getId() {

return id;

}

public long getAlbumId() {

return albumId;

}

}

2 新建MediaUtil類(lèi)用于從安卓媒體庫(kù)中獲取歌曲信息并保存在程序的List中,提供靜態(tài)方法給其他代碼來(lái)直接復(fù)用

public class MediaUtil {

//獲取專(zhuān)輯封面的Uri

private static final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");

//從安卓媒體庫(kù)中獲取歌曲信息并保存在程序的List中,并提供靜態(tài)方法給其他類(lèi)來(lái)直接獲得生成的歌曲列表信息

public static ListgetMp3InfoList(Context context){

Cursor cursor=context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,

null);

Listmp3InfoList=new ArrayList<>();

for(int i=0;i

cursor.moveToNext();

Mp3Info mp3Info=new Mp3Info();

mp3Info.setUrl(cursor.getString(cursor

.getColumnIndex(MediaStore.Audio.Media.DATA)));

mp3Info.setTitle(cursor.getString(cursor

.getColumnIndex(MediaStore.Audio.Media.TITLE)));

mp3Info.setArtist(cursor.getString(cursor

.getColumnIndex(MediaStore.Audio.Media.ARTIST)));

mp3Info.setDuration(cursor.getLong(cursor

.getColumnIndex(MediaStore.Audio.Media.DURATION)));

mp3Info.setId(cursor.getLong(cursor

.getColumnIndex(MediaStore.Audio.Media._ID)));

mp3Info.setAlbumId(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));

mp3InfoList.add(mp3Info);

}

return mp3InfoList;

}

/**

* 格式化時(shí)間,將毫秒轉(zhuǎn)換為分:秒格式//將long類(lèi)型轉(zhuǎn)化為String型,

* @param time

* @return

*/

public static String formatTime(long time) {

String min = time / (1000 * 60) + "";

String sec = time % (1000 * 60) + "";

if (min.length() < 2) {

min = "0" + time / (1000 * 60) + "";

} else {

min = time / (1000 * 60) + "";

}

if (sec.length() == 4) {

sec = "0" + (time % (1000 * 60)) + "";

} else if (sec.length() == 3) {

sec = "00" + (time % (1000 * 60)) + "";

} else if (sec.length() == 2) {

sec = "000" + (time % (1000 * 60)) + "";

} else if (sec.length() == 1) {

sec = "0000" + (time % (1000 * 60)) + "";

}

return min + ":" + sec.trim().substring(0, 2);

}

/**

* 獲取默認(rèn)專(zhuān)輯圖片

* @param context

* @return

*/

public static Bitmap getDefaultArtwork(Context context,boolean small) {

BitmapFactory.Options opts = new BitmapFactory.Options();

opts.inPreferredConfig = Bitmap.Config.RGB_565;

if(small){ //返回小圖片

return BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.music5), null, opts);

}

return BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.defaultalbum), null, opts);

}

/**

* 從文件當(dāng)中獲取專(zhuān)輯封面位圖

* @param context

* @param songid

* @param albumid

* @return

*/

private static Bitmap getArtworkFromFile(Context context, long songid, long albumid){

Bitmap bm = null;

if(albumid < 0 && songid < 0) {

throw new IllegalArgumentException("Must specify an album or a song id");

}

try {

BitmapFactory.Options options = new BitmapFactory.Options();

FileDescriptor fd = null;

if(albumid < 0){

Uri uri = Uri.parse("content://media/external/audio/media/"

+ songid + "/albumart");

ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");

if(pfd != null) {

fd = pfd.getFileDescriptor();

}

} else {

Uri uri = ContentUris.withAppendedId(albumArtUri, albumid);

ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");

if(pfd != null) {

fd = pfd.getFileDescriptor();

}

}

options.inSampleSize = 1;

// 只進(jìn)行大小判斷

options.inJustDecodeBounds = true;

// 調(diào)用此方法得到options得到圖片大小

BitmapFactory.decodeFileDescriptor(fd, null, options);

// 我們的目標(biāo)是在800pixel的畫(huà)面上顯示

// 所以需要調(diào)用computeSampleSize得到圖片縮放的比例

options.inSampleSize = 100;

// 我們得到了縮放的比例,現(xiàn)在開(kāi)始正式讀入Bitmap數(shù)據(jù)

options.inJustDecodeBounds = false;

options.inDither = false;

options.inPreferredConfig = Bitmap.Config.ARGB_8888;

//根據(jù)options參數(shù),減少所需要的內(nèi)存

bm = BitmapFactory.decodeFileDescriptor(fd, null, options);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

return bm;

}

/**

* 獲取專(zhuān)輯封面位圖對(duì)象

* @param context

* @param song_id

* @param album_id

* @param allowdefalut

* @return

*/

public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefalut, boolean small){

if(album_id < 0) {

if(song_id < 0) {

Bitmap bm = getArtworkFromFile(context, song_id, -1);

if(bm != null) {

return bm;

}

}

if(allowdefalut) {

return getDefaultArtwork(context, small);

}

return null;

}

ContentResolver res = context.getContentResolver();

Uri uri = ContentUris.withAppendedId(albumArtUri, album_id);

if(uri != null) {

InputStream in = null;

try {

in = res.openInputStream(uri);

BitmapFactory.Options options = new BitmapFactory.Options();

//先制定原始大小

options.inSampleSize = 1;

//只進(jìn)行大小判斷

options.inJustDecodeBounds = true;

//調(diào)用此方法得到options得到圖片的大小

BitmapFactory.decodeStream(in, null, options);

/** 我們的目標(biāo)是在你N pixel的畫(huà)面上顯示。 所以需要調(diào)用computeSampleSize得到圖片縮放的比例 **/

/** 這里的target為800是根據(jù)默認(rèn)專(zhuān)輯圖片大小決定的,800只是測(cè)試數(shù)字但是試驗(yàn)后發(fā)現(xiàn)完美的結(jié)合 **/

if(small){

options.inSampleSize = computeSampleSize(options, 40);

} else{

options.inSampleSize = computeSampleSize(options, 600);

}

// 我們得到了縮放比例,現(xiàn)在開(kāi)始正式讀入Bitmap數(shù)據(jù)

options.inJustDecodeBounds = false;

options.inDither = false;

options.inPreferredConfig = Bitmap.Config.ARGB_8888;

in = res.openInputStream(uri);

return BitmapFactory.decodeStream(in, null, options);

} catch (FileNotFoundException e) {

Bitmap bm = getArtworkFromFile(context, song_id, album_id);

if(bm != null) {

if(bm.getConfig() == null) {

bm = bm.copy(Bitmap.Config.RGB_565, false);

if(bm == null && allowdefalut) {

return getDefaultArtwork(context, small);

}

}

} else if(allowdefalut) {

bm = getDefaultArtwork(context, small);

}

return bm;

} finally {

try {

if(in != null) {

in.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

return null;

}

/**

* 對(duì)圖片進(jìn)行合適的縮放

* @param options

* @param target

* @return

*/

public static int computeSampleSize(BitmapFactory.Options options, int target) {

int w = options.outWidth;

int h = options.outHeight;

int candidateW = w / target;

int candidateH = h / target;

int candidate = Math.max(candidateW, candidateH);

if(candidate == 0) {

return 1;

}

if(candidate > 1) {

if((w > target) && (w / candidate) < target) {

candidate -= 1;

}

}

if(candidate > 1) {

if((h > target) && (h / candidate) < target) {

candidate -= 1;

}

}

return candidate;

}

}

3 活動(dòng)界面編程,這里直接上代碼

主界面:


xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

android:id="@+id/mainActivity_drawer_layout"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:id="@+id/mainActivity_toolBar"

android:layout_width="match_parent"

android:layout_height="?attr/actionBarSize"

android:background="?attr/colorPrimary"

android:popupTheme="@style/ThemeOverlay.AppCompat.Light"

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_below="@+id/mainActivity_toolBar"

android:background="#FFF">

android:id="@+id/musicName_list"

android:layout_width="match_parent"

android:layout_height="440dp"

android:textColor="#FFF"/>

android:id="@+id/mainActivity_seekBarLayout"

android:layout_width="match_parent"

android:layout_height="35dp"

android:layout_below="@+id/musicName_list"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:background="@drawable/drawable_bg">

android:id="@+id/mainActivity_seekBar"

android:layout_width="match_parent"

android:layout_height="20dp"

android:thumb="@drawable/media_player_progress_button"

/>

android:id="@+id/main_current_position"

android:layout_width="wrap_content"

android:layout_height="25dp"

android:layout_below="@id/mainActivity_seekBar"

android:text="0:00"

android:textColor="#060606"/>

android:id="@+id/main_final_position"

android:layout_width="wrap_content"

android:layout_height="25dp"

android:layout_alignParentRight="true"

android:layout_below="@id/mainActivity_seekBar"

android:text="3:00"

android:textColor="#090808"/>

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_alignParentBottom="true"

android:background="#7e7677"

android:layout_below="@+id/mainActivity_seekBarLayout">

android:id="@+id/album_view"

android:layout_width="80dp"

android:layout_height="match_parent"

/>

android:id="@+id/mainActivity_musicName"

android:layout_width="80dp"

android:layout_toRightOf="@+id/album_view"

android:layout_marginLeft="5dp"

android:layout_height="wrap_content"

android:text="歌曲名稱(chēng)"

android:textColor="#090909"/>

android:id="@+id/mainActivity_artist"

android:layout_width="80dp"

android:layout_height="wrap_content"

android:layout_below="@+id/mainActivity_musicName"

android:layout_marginLeft="5dp"

android:layout_toRightOf="@+id/album_view"

android:text="歌曲作者"

android:textColor="#060606"/>

android:id="@+id/mainActivity_play_pause"

android:layout_width="50dp"

android:layout_height="60dp"

android:layout_centerInParent="true"

android:layout_toLeftOf="@+id/mainActivity_next"

app:srcCompat="@drawable/play"/>

android:id="@+id/mainActivity_next"

android:layout_width="50dp"

android:layout_height="60dp"

android:layout_centerInParent="true"

app:srcCompat="@drawable/next"

android:layout_toLeftOf="@+id/mainActivity_menu"/>

android:id="@+id/mainActivity_menu"

android:layout_width="50dp"

android:layout_height="60dp"

android:layout_centerInParent="true"

android:layout_alignParentRight="true"

app:srcCompat="@drawable/menu"

/>

android:id="@+id/mainActivity_nav_view"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_gravity="start"

app:menu="@menu/nav_menu"

app:headerLayout="@layout/nav_header"

>

播放細(xì)節(jié)界面


xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#885959"

>

android:id="@+id/play_activity_toolBar1"

android:layout_width="match_parent"

android:layout_height="40dp"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

>

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/playActivity_return"

android:layout_width="45dp"

android:layout_height="30dp"

android:background="@drawable/back_return_normal"/>

android:id="@+id/playActivity_musicName"

android:layout_width="match_parent"

android:layout_height="20dp"

android:layout_toRightOf="@+id/playActivity_return"

android:text="歌曲名稱(chēng)"

android:layout_marginLeft="5dp"

android:textColor="#fcfcfc"/>

android:id="@+id/playActivity_artist"

android:layout_width="match_parent"

android:layout_marginLeft="5dp"

android:layout_height="20dp"

android:layout_toRightOf="@+id/playActivity_return"

android:layout_below="@+id/playActivity_musicName"

android:text="演唱者"

android:textColor="#c3b9b9"

/>

android:id="@+id/playActivity_musicLyrics"

android:layout_width="match_parent"

android:layout_height="400dp"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_above="@+id/playActivity_seekbarLayout">

android:id="@+id/playActivity_seekbarLayout"

android:layout_width="match_parent"

android:layout_height="35dp"

android:background="@drawable/drawable_bg"

android:layout_above="@+id/playActivity_toolBar2">

android:id="@+id/playActivity_seekBar"

android:layout_width="match_parent"

android:layout_height="20dp"

android:thumb="@drawable/media_player_progress_button"

/>

android:id="@+id/current_position"

android:layout_width="wrap_content"

android:layout_height="25dp"

android:layout_below="@id/playActivity_seekBar"

android:text="0:00"

android:textColor="#FFF"/>

android:id="@+id/final_position"

android:layout_width="wrap_content"

android:layout_height="25dp"

android:layout_alignParentRight="true"

android:layout_below="@id/playActivity_seekBar"

android:text="3:00"

android:textColor="#FFF"/>

android:id="@+id/playActivity_toolBar2"

android:layout_width="match_parent"

android:layout_height="70dp"

android:layout_alignParentBottom="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true">

android:id="@+id/stop"

android:layout_width="50dp"

android:layout_margin="10dp"

android:layout_height="match_parent"

app:srcCompat="@drawable/stop"/>

android:id="@+id/previous"

android:layout_width="50dp"

android:layout_margin="10dp"

android:layout_height="match_parent"

android:layout_toRightOf="@+id/stop"

app:srcCompat="@drawable/previous"/>

android:id="@+id/play_pause"

android:layout_margin="10dp"

android:layout_width="50dp"

android:layout_height="match_parent"

android:layout_toRightOf="@+id/previous"

app:srcCompat="@drawable/play"

/>

android:id="@+id/next_music"

android:layout_width="50dp"

android:layout_margin="10dp"

android:layout_height="match_parent"

android:layout_toRightOf="@+id/play_pause"

app:srcCompat="@drawable/next"

/>

android:id="@+id/music_menu"

android:layout_width="50dp"

android:layout_margin="10dp"

android:layout_height="match_parent"

android:layout_toRightOf="@+id/next_music"

app:srcCompat="@drawable/playqueue"

/>

4 MainActivity編程

public class MainActivity extends AppCompatActivity {

static ListView listView;

Listmp3InfoList;

Mp3Info mp3Info;

static int location=0;

static Boolean isPlaying=false;

List musicNameList=new ArrayList<>();

static TextView musicNameView;

static TextView artistView;

static ImageView albumView;

static ImageButton playOrPauseButton;

static ImageButton nextButton;

static SeekBar seekBar;

static TextView currentTiemView;

static TextView durationView;

DrawerLayout drawerLayout;

String Tag="MainActivity";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//ToolBar及DrawerLayout

Toolbar toolbar=(Toolbar)findViewById(R.id.mainActivity_toolBar);

setSupportActionBar(toolbar);

ActionBar actionBar=getSupportActionBar();

if(actionBar!=null){

actionBar.setDisplayHomeAsUpEnabled(true);

actionBar.setHomeAsUpIndicator(R.drawable.menu);

}

drawerLayout=(DrawerLayout)findViewById(R.id.mainActivity_drawer_layout);

//獲得各個(gè)控件并設(shè)置點(diǎn)擊事件

musicNameView=(TextView)findViewById(R.id.mainActivity_musicName);

artistView=(TextView)findViewById(R.id.mainActivity_artist);

playOrPauseButton=(ImageButton)findViewById(R.id.mainActivity_play_pause);

nextButton=(ImageButton)findViewById(R.id.mainActivity_next);

seekBar=(SeekBar)findViewById(R.id.mainActivity_seekBar);

currentTiemView=(TextView)findViewById(R.id.main_current_position) ;

durationView=(TextView)findViewById(R.id.main_final_position);

albumView=(ImageView)findViewById(R.id.album_view);

//設(shè)置各控件初始視圖為上次離開(kāi)時(shí)所播放的歌曲,如果進(jìn)程已被Kill掉,則為第一首

mp3InfoList=MediaUtil.getMp3InfoList(MainActivity.this);

mp3Info=mp3InfoList.get(location);

musicNameView.setText(mp3Info.getTitle());

artistView.setText(mp3Info.getArtist());

long id=mp3Info.getId();

long albumId=mp3Info.getAlbumId();

albumView.setImageBitmap(MediaUtil.getArtwork(this, id,

albumId, true, false));

if(isPlaying)

playOrPauseButton.setImageResource(R.drawable.pause);

else playOrPauseButton.setImageResource(R.drawable.play);

//專(zhuān)輯圖片點(diǎn)擊事件,進(jìn)入PlayActivity中,并通過(guò)Intent傳遞location和isPlaying狀態(tài)

albumView.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

Intent intent=new Intent(MainActivity.this,PlayActivity.class);

intent.putExtra("state",isPlaying);

intent.putExtra("location",location);

startActivity(intent);

}

});

//暫停、播放按鈕點(diǎn)擊事件

playOrPauseButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

playOrpause();

}

});

//下一首點(diǎn)擊事件

nextButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

nextMusic();

}

});

//從媒體庫(kù)中獲得音樂(lè)列表并顯示到ListView中,同時(shí)設(shè)置點(diǎn)擊事件

listView=(ListView)findViewById(R.id.musicName_list) ;

for(int i=0;i

musicNameList.add(mp3InfoList.get(i).getTitle());

ArrayAdapter aa=new ArrayAdapter(this,android.R.layout.simple_list_item_1,musicNameList);

listView.setAdapter(aa);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView adapterView, View view, int i, long l) {

location=i;

setPlay(location);

}

});

//注冊(cè)監(jiān)聽(tīng)SeekBar變化的監(jiān)聽(tīng)器

IntentFilter filter=new IntentFilter();

filter.addAction("com.example.musicplayer.update_seekbar");

UpdateSeekbarBroadcast receiver=new UpdateSeekbarBroadcast();

registerReceiver(receiver,filter);

//監(jiān)聽(tīng)PlayActivity的點(diǎn)擊事件

IntentFilter filter1=new IntentFilter();

filter1.addAction("com.example.musicplayer.react_to_playactiity");

PlayActivityBroadcast receiver1=new PlayActivityBroadcast();

registerReceiver(receiver1,filter1);

//注冊(cè)監(jiān)聽(tīng)Notification的監(jiān)聽(tīng)器

IntentFilter filter2=new IntentFilter();

filter2.addAction("com.example.musicplayer.notification.previous");

filter2.addAction("com.example.musicplayer.notification.play_pause");

filter2.addAction("com.example.musicplayer.notification.next");

NotificationBroadcast receiver2=new NotificationBroadcast();

registerReceiver(receiver2,filter2);

//注冊(cè)監(jiān)聽(tīng)后臺(tái)順序播放的監(jiān)聽(tīng)器

IntentFilter filter3=new IntentFilter();

filter3.addAction("com.example.musicplayer.order_play");

OrderPlayBroadcast receiver3=new OrderPlayBroadcast();

registerReceiver(receiver3,filter3);

//為SeekBar設(shè)置點(diǎn)擊拖動(dòng)事件

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

@Override

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

}

@Override

public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override

public void onStopTrackingTouch(SeekBar seekBar) {

int progress=seekBar.getProgress();

Intent intent=new Intent(MainActivity.this, MusicService.class);

intent.putExtra("tag",2);

intent.putExtra("progress",progress);

startService(intent);

}

});

}

public boolean onCreateOptionsMenu(Menu menu){

getMenuInflater().inflate(R.menu.toolbar,menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem menuItem){

switch (menuItem.getItemId()){

case android.R.id.home:drawerLayout.openDrawer(GravityCompat.START);

break;

case R.id.search:

Toast.makeText(MainActivity.this,"You clicked the search button",Toast.LENGTH_SHORT).show();

break;

}

return true;

}

//設(shè)置播放某一首歌曲

public void setPlay(int location){

//切換播放狀態(tài)

isPlaying=true;

//根據(jù)要播放的音樂(lè)曲目更新MainActivity的UI

mp3Info=mp3InfoList.get(location);

long id=mp3Info.getId();

long albumId=mp3Info.getAlbumId();

musicNameView.setText(mp3Info.getTitle());

artistView.setText(mp3Info.getArtist());

Bitmap bitmap = MediaUtil.getArtwork(this, id,

albumId, true, false);// 獲取專(zhuān)輯位圖對(duì)象,為大圖

albumView.setImageBitmap(bitmap);

//切換播放狀態(tài)圖標(biāo)

playOrPauseButton.setImageResource(R.drawable.pause);

seekBar.setMax((int)mp3Info.getDuration());

currentTiemView.setText("0:00");

durationView.setText(MediaUtil.formatTime(mp3Info.getDuration()));

//傳遞歌曲下標(biāo)location并啟動(dòng)服務(wù)

Intent intent=new Intent(MainActivity.this,MusicService.class);

intent.putExtra("tag",0);

intent.putExtra("location",location);

startService(intent);

}

//播放下一首歌曲

public void nextMusic(){

if((++location)

setPlay(location);

}

}

//播放上一首歌曲

public void previousMusic(){

if ((--location)>=0){

setPlay(location);

}

}

//暫?;蚶^續(xù)播放

public void playOrpause(){

Intent intent=new Intent(MainActivity.this,MusicService.class);

//切換播放狀態(tài)并改變狀態(tài)圖標(biāo)

isPlaying=!isPlaying;

if(isPlaying)

playOrPauseButton.setImageResource(R.drawable.pause);

else playOrPauseButton.setImageResource(R.drawable.play);

intent.putExtra("tag",1);

intent.putExtra("state",isPlaying);

startService(intent);

}

//停止播放此首音樂(lè),并將進(jìn)度條滑至開(kāi)始處

public void stopMusic(){

Intent intent=new Intent(MainActivity.this,MusicService.class);

intent.putExtra("tag",3);

if(isPlaying)

playOrPauseButton.setImageResource(R.drawable.play);

else playOrPauseButton.setImageResource(R.drawable.pause);

startService(intent);

}

//監(jiān)聽(tīng)來(lái)自Service的SeekBar變化

class UpdateSeekbarBroadcast extends BroadcastReceiver{

@Override

public void onReceive(Context context,Intent intent){

int position=intent.getIntExtra("position",0);

currentTiemView.setText(MediaUtil.formatTime(position));

seekBar.setProgress(position);

}

}

//接收來(lái)自PlayActivity的廣播

class PlayActivityBroadcast extends BroadcastReceiver{

@Override

public void onReceive(Context context,Intent intent){

int tag1=intent.getIntExtra("tag1",-1);

switch (tag1){

case 0: {

playOrpause();

}

break;

case 1:previousMusic();

break;

case 2:nextMusic();

break;

case 3:stopMusic();

default:

break;

case 4:{

location=intent.getIntExtra("location",5);

setPlay(location);

}

}

}

}

//接收來(lái)自Notification的廣播

class NotificationBroadcast extends BroadcastReceiver{

@Override

public void onReceive(Context context,Intent intent){

int tag2=intent.getIntExtra("tag2",-1);

LogUtil.d(Tag,"received the broadcast from notification");

switch (tag2){

case 0:previousMusic();

break;

case 1:{

playOrpause();

isPlaying=intent.getBooleanExtra("state",false);

}

break;

case 2:nextMusic();

break;

default:

break;

}

}

}

//接收來(lái)自后臺(tái)自動(dòng)播放的廣播以更新UI

class OrderPlayBroadcast extends BroadcastReceiver{

@Override

public void onReceive(Context context,Intent intent){

LogUtil.d(Tag,"update ui according to the orderly play");

location=intent.getIntExtra("location",-1);

mp3Info=mp3InfoList.get(location);

long id=mp3Info.getId();

long albumId=mp3Info.getAlbumId();

musicNameView.setText(mp3Info.getTitle());

artistView.setText(mp3Info.getArtist());

Bitmap bitmap = MediaUtil.getArtwork(MainActivity.this, id,

albumId, true, false);// 獲取專(zhuān)輯位圖對(duì)象,為大圖

albumView.setImageBitmap(bitmap);

seekBar.setMax((int)mp3Info.getDuration());

currentTiemView.setText("0:00");

durationView.setText(MediaUtil.formatTime(mp3Info.getDuration()));

}

}

}

PlayActivity

public class PlayActivity extends AppCompatActivity implements View.OnClickListener {

TextView musicNameView,artistView;

Button returnBack;

ImageButton stop,previousMusic,playOrPauseButton,nextMusic,musicList;

SeekBar seekBar;

TextView currentTimeView,durationView;

Intent intent;

static int location=0;

static Boolean isPlaying=false;

Mp3Info mp3Info;

Listmp3InfoList=new ArrayList<>();

String[]musicNameList;

String Tag="PlayActivity";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_play);

//獲得歌曲列表信息

mp3InfoList=MediaUtil.getMp3InfoList(PlayActivity.this);

//獲得各控件實(shí)例

musicNameView=(TextView)findViewById(R.id.playActivity_musicName) ;

artistView=(TextView)findViewById(R.id.playActivity_artist);

stop=(ImageButton)findViewById(R.id.stop);

previousMusic=(ImageButton)findViewById(R.id.previous);

playOrPauseButton=(ImageButton)findViewById(R.id.play_pause);

nextMusic=(ImageButton)findViewById(R.id.next_music);

musicList=(ImageButton)findViewById(R.id.music_menu);

returnBack=(Button)findViewById(R.id.playActivity_return);

seekBar=(SeekBar)findViewById(R.id.playActivity_seekBar);

currentTimeView=(TextView)findViewById(R.id.current_position);

durationView=(TextView)findViewById(R.id.final_position);

//從MainActivity中傳遞過(guò)來(lái)的數(shù)據(jù)

Intent intent1=getIntent();

location=intent1.getIntExtra("location",0);

isPlaying=intent1.getBooleanExtra("state",false);

//根據(jù)傳遞過(guò)來(lái)的數(shù)據(jù)更新UI視圖

seekBar.setMax((int)(mp3InfoList.get(location).getDuration()));

currentTimeView.setText("0:00");

durationView.setText(MediaUtil.formatTime(mp3InfoList.get(location).getDuration()));

musicNameView.setText(mp3InfoList.get(location).getTitle());

artistView.setText(mp3InfoList.get(location).getArtist());

durationView.setText(MediaUtil.formatTime(mp3InfoList.get(location).getDuration()));

if(isPlaying)

playOrPauseButton.setImageResource(R.drawable.pause);

else playOrPauseButton.setImageResource(R.drawable.play);

//注冊(cè)seekBar監(jiān)聽(tīng)器

IntentFilter filter=new IntentFilter();

filter.addAction("com.example.musicplayer.update_seekbar");

UpdateSeekbarBroadcast receiver=new UpdateSeekbarBroadcast();

registerReceiver(receiver,filter);

//注冊(cè)后臺(tái)順序播放的監(jiān)聽(tīng)器

IntentFilter filter1=new IntentFilter();

filter1.addAction("com.example.musicplayer.order_play");

OrderPlayBroadcast receiver1=new OrderPlayBroadcast();

registerReceiver(receiver1,filter1);

//為SeekBar設(shè)置點(diǎn)擊拖動(dòng)事件

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

@Override

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

}

@Override

public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override

public void onStopTrackingTouch(SeekBar seekBar) {

int progress=seekBar.getProgress();

Intent intent=new Intent(PlayActivity.this, MusicService.class);

intent.putExtra("tag",2);

intent.putExtra("progress",progress);

startService(intent);

}

});

//設(shè)置各按鈕點(diǎn)擊事件

stop.setOnClickListener(this);

previousMusic.setOnClickListener(this);

playOrPauseButton.setOnClickListener(this);

nextMusic.setOnClickListener(this);

musicList.setOnClickListener(this);

}

//監(jiān)聽(tīng)來(lái)自Service的SeekBar變化

class UpdateSeekbarBroadcast extends BroadcastReceiver{

@Override

public void onReceive(Context context,Intent intent){

int position=intent.getIntExtra("position",0);

currentTimeView.setText(MediaUtil.formatTime(position));

seekBar.setProgress(position);

}

}

//接收來(lái)自后臺(tái)自動(dòng)播放的廣播以更新UI

class OrderPlayBroadcast extends BroadcastReceiver{

@Override

public void onReceive(Context context,Intent intent){

LogUtil.d(Tag,"PlayActivity receive broadcast from service orderly play to update UI ");

location=intent.getIntExtra("location",-1);

mp3Info=mp3InfoList.get(location);

musicNameView.setText(mp3Info.getTitle());

artistView.setText(mp3Info.getArtist());

seekBar.setMax((int)mp3Info.getDuration());

currentTimeView.setText("0:00");

durationView.setText(MediaUtil.formatTime(mp3Info.getDuration()));

}

}

@Override

public void onClick(View view){

Intent intent=new Intent("com.example.musicplayer.react_to_playactiity");

switch (view.getId()){

case R.id.stop :{

intent.putExtra("tag1",3);

}

break;

case R.id.previous: {

isPlaying=!isPlaying;

previousMusic();

intent.putExtra("tag1", 1);

}

break;

case R.id.play_pause:{

isPlaying=!isPlaying;

if(isPlaying) {

playOrPauseButton.setImageResource(R.drawable.pause);

}

else {

playOrPauseButton.setImageResource(R.drawable.play);

}

intent.putExtra("tag1",0);

intent.putExtra("state",isPlaying);

}

break;

case R.id.next_music:{

nextMusic();

intent.putExtra("tag1",2);

}

break;

case R.id.music_menu:

Log.d("PlayActivity","press the button music_menu");

showMusicList();

break;

default:

break;

}

sendBroadcast(intent);

}

//根據(jù)點(diǎn)擊事件更新UI視圖

public void previousMusic(){

if((--location)>=0)

{

seekBar.setMax((int)(mp3InfoList.get(location).getDuration()));

currentTimeView.setText("0:00");

durationView.setText(MediaUtil.formatTime(mp3InfoList.get(location).getDuration()));

musicNameView.setText(mp3InfoList.get(location).getTitle());

artistView.setText(mp3InfoList.get(location).getArtist());

playOrPauseButton.setImageResource(R.drawable.pause);

}

}

public void nextMusic(){

if((++location)>=0)

{

seekBar.setMax((int)(mp3InfoList.get(location).getDuration()));

currentTimeView.setText("0:00");

durationView.setText(MediaUtil.formatTime(mp3InfoList.get(location).getDuration()));

musicNameView.setText(mp3InfoList.get(location).getTitle());

artistView.setText(mp3InfoList.get(location).getArtist());

playOrPauseButton.setImageResource(R.drawable.pause);

}

}

//通過(guò)AlertDialog顯示歌曲列表

public void showMusicList(){

Log.d("PlayActivity","showMusicList start");

LinearLayout linearLayoutMain = new LinearLayout(this);//自定義一個(gè)布局文件

linearLayoutMain.setLayoutParams(new LinearLayoutCompat.LayoutParams(

LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

Log.d("PlayActivity","LinearLayout created");

ListView listView = new ListView(this);//this為獲取當(dāng)前的上下文

listView.setFadingEdgeLength(0);

List>musicList=new ArrayList>();

for(int i=0;i

Mapitem=new HashMap();

item.put("musicName",mp3InfoList.get(i).getTitle().toString());

item.put("artist",mp3InfoList.get(i).getArtist().toString());

musicList.add(item);

}

Log.d("PlayActivity","LinearLayout created and itialized");

SimpleAdapter adapter=new SimpleAdapter(PlayActivity.this,musicList,R.layout.music_item

,new String[]{"musicName","artist"}

, new int[]{R.id.music_item_musicName,R.id.music_item_artist});

Log.d("PlayActivity","SimpleAdapter created");

listView.setAdapter(adapter);

linearLayoutMain.addView(listView);

Log.d("PlayActivity","listView was added to the linearLayout");

final AlertDialog dialog=new AlertDialog.Builder(this).setTitle("歌曲列表").setView(linearLayoutMain)

.setNegativeButton("取消", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

// TODO Auto-generated method stub

dialog.cancel();

}

}).create();

Log.d("PlayActivity","Dialog created");

dialog.show();

Log.d("PlayActivity","Dialog showed");

//響應(yīng)子項(xiàng)點(diǎn)擊事件

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView adapterView, View view, int i, long l) {

//更新自身UI

musicNameView.setText(mp3InfoList.get(i).getTitle());

artistView.setText(mp3InfoList.get(i).getArtist());

durationView.setText(MediaUtil.formatTime(mp3InfoList.get(i).getDuration()));

//發(fā)送廣播附帶歌曲下標(biāo)給MainActivity來(lái)控制服務(wù)播放歌曲

Intent intent=new Intent("com.example.musicplayer.react_to_playactiity");

intent.putExtra("tag1",4);

intent.putExtra("location",i);

sendBroadcast(intent);

Log.d("PlayActivity","broadcast sended");

dialog.cancel();

Log.d("PlayActivity","Dialog canceled");

}

});

}

}

5 ?MusicService 創(chuàng)建服務(wù)類(lèi)

public class MusicService extends Service {

List mp3InfoList = new ArrayList<>();

MediaPlayer mediaPlayer;

Mp3Info mp3Info;

Notification notification;

static int location;

int position;

static Boolean isPlaying=false;

RemoteViews contecntViews;

public MusicService() {

}

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

public void onCreate() {

super.onCreate();

mediaPlayer=new MediaPlayer();

//獲得歌曲Mp3Info類(lèi)列表

mp3InfoList = MediaUtil.getMp3InfoList(MusicService.this);

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Log.d("MusicService", "service onStartommand");

int tag= intent.getIntExtra("tag", -1);

switch (tag) {

case 0: {

isPlaying=true;

location=intent.getIntExtra("location",-1);

mp3Info=mp3InfoList.get(location);

String url = mp3Info.getUrl();

String title=mp3Info.getTitle();

String artist=mp3Info.getArtist();

long id=mp3Info.getId();

long albumId=mp3Info.getAlbumId();

try {

if (mediaPlayer != null) {

mediaPlayer.reset();

}

mediaPlayer.setDataSource(this, Uri.parse(url));

mediaPlayer.prepare();

mediaPlayer.start();

showNotification(title,artist,id,albumId);

} catch (IOException e) {

e.printStackTrace();

}

}break;

case 1:{

if(mediaPlayer!=null) {

if (mediaPlayer.isPlaying()) {

mediaPlayer.pause();

} else mediaPlayer.start();

}

isPlaying=intent.getBooleanExtra("state",false);

if(isPlaying==true)

isPlaying=false;

else

isPlaying=true;

}break;

case 2:{

isPlaying=true;

int progress=intent.getIntExtra("progress",0);

if(mediaPlayer!=null){

mediaPlayer.seekTo(progress);

}

}break;

case 3:{

mediaPlayer.stop();

try{

mediaPlayer.prepare();

mediaPlayer.seekTo(0);}

catch (Exception e){

e.printStackTrace();

}

} break;

}

//

new PlayProgress().execute();

//設(shè)置自動(dòng)播放下一首

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

@Override

public void onCompletion(MediaPlayer mediaPlayer) {

if(mediaPlayer!=null){

try {

if (++location < mp3InfoList.size()) {

mediaPlayer.reset();

mediaPlayer.setDataSource(MusicService.this, Uri.parse(mp3InfoList.get(location).getUrl()));

mediaPlayer.prepare();

mediaPlayer.start();

}

}catch (Exception e){

e.printStackTrace();

}

}

//通過(guò)發(fā)送廣播讓MainActivity,PlayActivity更新UI

Intent intent=new Intent("com.example.musicplayer.order_play");

intent.putExtra("location",location);

sendBroadcast(intent);

//后臺(tái)更新NotificationUI

isPlaying=true;

mp3Info=mp3InfoList.get(location);

String title=mp3Info.getTitle();

String artist=mp3Info.getArtist();

long id=mp3Info.getId();

long albumId=mp3Info.getAlbumId();

showNotification(title,artist,id,albumId);

}

});

return super.onStartCommand(intent, flags, startId);

}

public class PlayProgress extends AsyncTask{

@Override

public void onPreExecute(){

super.onPreExecute();

}

@Override

public Integer doInBackground(Void...parms){

while (true){

try{

Thread.sleep(500);

}

catch (Exception e){

e.printStackTrace();

}

position=mediaPlayer.getCurrentPosition();

if(position

Intent mIntent=new Intent("com.example.musicplayer.update_seekbar");

mIntent.putExtra("position",position);

sendBroadcast(mIntent);

}else{

break;

}

}

return 0;

}

@Override

protected void onPostExecute(Integer integer) {

Log.d("===","異步類(lèi)執(zhí)行完畢");

super.onPostExecute(integer);

}

}

//通知欄

public void showNotification(String title, String artist, long id, long albumId){

NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

NotificationCompat.Builder builder= new NotificationCompat.Builder(this);

contecntViews =new RemoteViews(getPackageName(),R.layout.notification_music);

contecntViews.setTextViewText(R.id.notification_musicName,title);

contecntViews.setTextViewText(R.id.notification_artist,artist);

Bitmap bitmap = MediaUtil.getArtwork(this, id,

albumId, true, false);// 獲取專(zhuān)輯位圖對(duì)象,為大圖

contecntViews.setImageViewBitmap(R.id.notification_imageView,bitmap);

contecntViews.setOnClickPendingIntent(R.id.notification_previousMusic,PendingIntent.getBroadcast(this,0,

new Intent("com.example.musicplayer.notification.previous").putExtra("tag2",0), PendingIntent.FLAG_UPDATE_CURRENT));

contecntViews.setOnClickPendingIntent(R.id.notification_play_pause,PendingIntent.getBroadcast(this,0,

new Intent("com.example.musicplayer.notification.play_pause").putExtra("tag2",1).putExtra("state",!isPlaying), PendingIntent.FLAG_UPDATE_CURRENT));

contecntViews.setOnClickPendingIntent(R.id.notification_next,PendingIntent.getBroadcast(this,0,

new Intent("com.example.musicplayer.notification.next").putExtra("tag2",2), PendingIntent.FLAG_UPDATE_CURRENT));

notification=builder.setContent(contecntViews).setSmallIcon(R.mipmap.ic_launcher).build();

manager.notify(0,notification);

}

@Override

public void onDestroy(){

super.onDestroy();

mediaPlayer.stop();

mediaPlayer.release();

}

}

上面就是這個(gè)Demo的全部?jī)?nèi)容,還有很多不足(也可以說(shuō)是不少bug)和程序運(yùn)行期間會(huì)出現(xiàn)一些閃退的現(xiàn)象,限于本人目前水平有限,希望日后經(jīng)過(guò)更深入學(xué)習(xí)能回來(lái)解決現(xiàn)在留下的問(wèn)題。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線程,因...
    小菜c閱讀 7,317評(píng)論 0 17
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,917評(píng)論 25 709
  • 在Android中播放音頻文件一般都是使用MediaPlayer類(lèi)來(lái)實(shí)現(xiàn)的 MediaPlayer使用步驟簡(jiǎn)介: ...
    大話程序閱讀 1,683評(píng)論 0 12
  • #Android 基礎(chǔ)知識(shí)點(diǎn)總結(jié) ---------- ##1.adb - android debug bridg...
    Mythqian閱讀 3,723評(píng)論 2 11
  • 首先,我是個(gè)不愛(ài)搶的人; 這個(gè)活原來(lái)是老大讓我做的,但是,是她項(xiàng)目上的,于是,我讓他了解了事情的情況,然后每個(gè)過(guò)程...
    林小夏199閱讀 386評(píng)論 0 1

友情鏈接更多精彩內(nèi)容