Android基于Service的音樂播放器
本文開發(fā)一個基于Service的音樂播放器,音樂由后臺運(yùn)行的Service負(fù)責(zé)播放,當(dāng)后臺的播放狀態(tài)發(fā)生變化時,程序?qū)ㄟ^發(fā)送廣播通知前臺Activity更新界面;當(dāng)點(diǎn)擊Activity的界面按鈕時,系統(tǒng)將通過發(fā)送廣播通知后臺Service來改變播放狀態(tài)。
前臺Activity界面有兩個按鈕,分別用于控制播放/暫停、停止,另外還有兩個文本框,用于顯示正在播放的歌曲名、歌手名。前臺Activity的代碼如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ImageButton mStart;
private ImageButton mStop;
private TextView mMusicName;
private TextView mSongerName;
private ActivityReceiver mActivityReceiver;
public static final String CTL_ACTION = "com.trampcr.action.CTL_ACTION";
public static final String UPDATE_ACTION = "com.trampcr.action.UPDATE_ACTION";
//定義音樂播放狀態(tài),0x11代表沒有播放,0x12代表正在播放,0x13代表暫停
int status = 0x11;
String[] musicNames = new String[]{"完美生活", "那一年", "故鄉(xiāng)"};
String[] songerNames = new String[]{"許巍", "許巍", "許巍"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStart = (ImageButton) findViewById(R.id.start);
mStop = (ImageButton) findViewById(R.id.stop);
mMusicName = (TextView) findViewById(R.id.music_name);
mSongerName = (TextView) findViewById(R.id.songer_name);
mStart.setOnClickListener(this);
mStop.setOnClickListener(this);
mActivityReceiver = new ActivityReceiver();
//創(chuàng)建IntentFilter
IntentFilter filter = new IntentFilter();
//指定BroadcastReceiver監(jiān)聽的Action
filter.addAction(UPDATE_ACTION);
//注冊BroadcastReceiver
registerReceiver(mActivityReceiver, filter);
Intent intent = new Intent(MainActivity.this, MusicService.class);
//啟動后臺Service
startService(intent);
}
public class ActivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//獲取Intent中的update消息,update代表播放狀態(tài)
int update = intent.getIntExtra("update", -1);
//獲取Intent中的current消息,current代表當(dāng)前正在播放的歌曲
int current = intent.getIntExtra("current", -1);
if (current >= 0){
mMusicName.setText(musicNames[current]);
mSongerName.setText(songerNames[current]);
}
switch (update){
case 0x11:
mStart.setBackgroundResource(R.drawable.play);
status = 0x11;
break;
//控制系統(tǒng)進(jìn)入播放狀態(tài)
case 0x12:
//在播放狀態(tài)下設(shè)置使用暫停圖標(biāo)
mStart.setBackgroundResource(R.drawable.pause);
status = 0x12;
break;
case 0x13:
//在暫停狀態(tài)下設(shè)置使用播放圖標(biāo)
mStart.setBackgroundResource(R.drawable.play);
status = 0x13;
break;
}
}
}
@Override
public void onClick(View v) {
Intent intent = new Intent(CTL_ACTION);
switch (v.getId()){
case R.id.start:
intent.putExtra("control", 1);
break;
case R.id.stop:
intent.putExtra("control", 2);
break;
}
//發(fā)送廣播,將被Service中的BroadcastReceiver接收到
sendBroadcast(intent);
}
}
ActivityReceiver()用于響應(yīng)后臺Service所發(fā)出的廣播,該程序?qū)鶕?jù)廣播Intent里的消息來改變播放狀態(tài),并更新程序界面中按鈕的圖標(biāo)。
onClick中根據(jù)點(diǎn)擊的按鈕發(fā)送廣播,發(fā)送廣播時會把所按下的按鈕標(biāo)識發(fā)送出來。
接下來是后臺Service,會在播放狀態(tài)發(fā)生改變時對外發(fā)送廣播。代碼如下:
public class MusicService extends Service {
MyReceiver serviceReceiver;
AssetManager mAssetManager;
String[] musics = new String[]{"prefectLife.mp3", "thatYear.mp3", "country.mp3"};
MediaPlayer mMediaPlayer;
int status = 0x11;
int current = 0; // 記錄當(dāng)前正在播放的音樂
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mAssetManager = getAssets();
serviceReceiver = new MyReceiver();
//創(chuàng)建IntentFilter
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.CTL_ACTION);
registerReceiver(serviceReceiver, filter);
//創(chuàng)建MediaPlayer
mMediaPlayer = new MediaPlayer();
//為MediaPlayer播放完成事件綁定監(jiān)聽器
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
current++;
if (current >= 3) {
current = 0;
}
//發(fā)送廣播通知Activity更改文本框
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("current", current);
//發(fā)送廣播,將被Activity中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
//準(zhǔn)備并播放音樂
prepareAndPlay(musics[current]);
}
});
}
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int control = intent.getIntExtra("control", -1);
switch (control){
case 1: // 播放或暫停
//原來處于沒有播放狀態(tài)
if (status ==0x11){
//準(zhǔn)備播放音樂
prepareAndPlay(musics[current]);
status = 0x12;
}
//原來處于播放狀態(tài)
else if (status == 0x12){
//暫停
mMediaPlayer.pause();
status = 0x13; // 改變?yōu)闀和顟B(tài)
}
//原來處于暫停狀態(tài)
else if (status == 0x13){
//播放
mMediaPlayer.start();
status = 0x12; // 改變狀態(tài)
}
break;
//停止聲音
case 2:
//如果原來正在播放或暫停
if (status == 0x12 || status == 0x13){
//停止播放
mMediaPlayer.stop();
status = 0x11;
}
}
//廣播通知Activity更改圖標(biāo)、文本框
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("update", status);
sendIntent.putExtra("current", current);
//發(fā)送廣播,將被Activity中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
}
}
private void prepareAndPlay(String music) {
try {
//打開指定的音樂文件
AssetFileDescriptor assetFileDescriptor = mAssetManager.openFd(music);
mMediaPlayer.reset();
//使用MediaPlayer加載指定的聲音文件
mMediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
mMediaPlayer.prepare(); // 準(zhǔn)備聲音
mMediaPlayer.start(); // 播放
} catch (IOException e) {
e.printStackTrace();
}
}
}
MyReceiver用于接收前臺Activity所發(fā)出的廣播,并根據(jù)廣播的消息內(nèi)容改變Service的播放狀態(tài),當(dāng)播放狀態(tài)改變時,該Service對外發(fā)送一條廣播,廣播消息將會被前臺Activity接收,前臺Activity將會根據(jù)廣播消息更新界面。
為了讓該音樂播放器能按順序依次播放歌曲,程序為MediaPlayer增加了OnCompletionListener監(jiān)聽器,當(dāng)MediaPlayer播放完成后將自動播放下一首歌曲。
運(yùn)行程序,效果圖如下:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android使用CountDownTimer模擬短信驗證倒計時
這篇文章主要為大家詳細(xì)介紹了Android使用CountDownTimer模擬短信驗證倒計時,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-07-07
Android SharedPreferences實(shí)現(xiàn)數(shù)據(jù)存儲功能
這篇文章主要為大家詳細(xì)介紹了Android SharedPreferences實(shí)現(xiàn)數(shù)據(jù)存儲功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
Android實(shí)現(xiàn)返回拍攝的圖片功能實(shí)例
這篇文章主要介紹了Android實(shí)現(xiàn)返回拍攝的圖片功能,以實(shí)例形式較為詳細(xì)的分析了Android返回拍攝圖片功能的具體步驟與實(shí)現(xiàn)方法,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
Android自定義控件實(shí)現(xiàn)底部菜單(上)
這篇文章主要為大家詳細(xì)介紹了Android自定義控件實(shí)現(xiàn)底部菜單的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01
Android Studio使用USB真機(jī)調(diào)試詳解
這篇文章主要為大家詳細(xì)介紹了Android Studio使用USB真機(jī)調(diào)試的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
Android 中ListView點(diǎn)擊Item無響應(yīng)問題的解決辦法
如果listitem里面包括button或者checkbox等控件,默認(rèn)情況下listitem會失去焦點(diǎn),導(dǎo)致無法響應(yīng)item的事件,怎么解決呢?下面小編給大家分享下listview點(diǎn)擊item無響應(yīng)的解決辦法2016-12-12
Flutter啟動頁(閃屏頁)的具體實(shí)現(xiàn)及原理詳析
這篇文章主要給大家介紹了關(guān)于Flutter啟動頁(閃屏頁)的具體實(shí)現(xiàn)及原理的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Flutter具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

