Android基於Service的音樂播放器_Android

來源:互聯網
上載者:User

本文開發一個基於Service的音樂播放器,音樂由後台啟動並執行Service負責播放,當背景播放狀態發生變化時,程式將會通過發送廣播通知前台Activity更新介面;當點擊Activity的介面按鈕時,系統將通過發送廣播通知後台Service來改變播放狀態。

前台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";  //定義音樂播放狀態,0x11代表沒有播放,0x12代表現正播放,0x13代表暫停  int status = 0x11;  String[] musicNames = new String[]{"完美生活", "那一年", "故鄉"};  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();    //建立IntentFilter    IntentFilter filter = new IntentFilter();    //指定BroadcastReceiver監聽的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代表播放狀態      int update = intent.getIntExtra("update", -1);      //擷取Intent中的current訊息,current代表當前現正播放的歌曲      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;        //控制系統進入播放狀態        case 0x12:          //在播放狀態下設定使用暫停表徵圖          mStart.setBackgroundResource(R.drawable.pause);          status = 0x12;          break;        case 0x13:          //在暫停狀態下設定使用播放表徵圖          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;    }    //發送廣播,將被Service中的BroadcastReceiver接收到    sendBroadcast(intent);  }}

ActivityReceiver()用於響應後台Service所發出的廣播,該程式將會根據廣播Intent裡的訊息來改變播放狀態,並更新程式介面中按鈕的表徵圖。

onClick中根據點擊的按鈕發送廣播,發送廣播時會把所按下的按鈕標識發送出來。

接下來是後台Service,會在播放狀態發生改變時對外發送廣播。代碼如下:

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; // 記錄當前現正播放的音樂  @Nullable  @Override  public IBinder onBind(Intent intent) {    return null;  }  @Override  public void onCreate() {    super.onCreate();    mAssetManager = getAssets();    serviceReceiver = new MyReceiver();    //建立IntentFilter    IntentFilter filter = new IntentFilter();    filter.addAction(MainActivity.CTL_ACTION);    registerReceiver(serviceReceiver, filter);    //建立MediaPlayer    mMediaPlayer = new MediaPlayer();    //為MediaPlayer播放完成事件綁定監聽器    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {      @Override      public void onCompletion(MediaPlayer mp) {        current++;        if (current >= 3) {          current = 0;        }        //發送廣播通知Activity更改文字框        Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);        sendIntent.putExtra("current", current);        //發送廣播,將被Activity中的BroadcastReceiver接收到        sendBroadcast(sendIntent);        //準備並播放音樂        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: // 播放或暫停          //原來處於沒有播放狀態          if (status ==0x11){            //準備播放音樂            prepareAndPlay(musics[current]);            status = 0x12;          }          //原來處於播放狀態          else if (status == 0x12){            //暫停            mMediaPlayer.pause();            status = 0x13; // 改變為暫停狀態          }          //原來處於暫停狀態          else if (status == 0x13){            //播放            mMediaPlayer.start();            status = 0x12; // 改變狀態          }          break;        //停止聲音        case 2:          //如果原來現正播放或暫停          if (status == 0x12 || status == 0x13){            //停止播放            mMediaPlayer.stop();            status = 0x11;          }      }      //廣播通知Activity更改表徵圖、文字框      Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);      sendIntent.putExtra("update", status);      sendIntent.putExtra("current", current);      //發送廣播,將被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(); // 準備聲音      mMediaPlayer.start(); // 播放    } catch (IOException e) {      e.printStackTrace();    }  }}

MyReceiver用於接收前台Activity所發出的廣播,並根據廣播的訊息內容改變Service的播放狀態,當播放狀態改變時,該Service對外發送一條廣播,廣播訊息將會被前台Activity接收,前台Activity將會根據廣播訊息更新介面。

為了讓該音樂播放器能按順序依次播放歌曲,程式為MediaPlayer增加了OnCompletionListener監聽器,當MediaPlayer播放完成後將自動播放下一首歌曲。

運行程式,效果圖如下:


以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.