Android Mediaplayer本地音樂播放器(綁定服務)

來源:互聯網
上載者:User

標籤:android   mediaplayer   音樂   播放器   

本文章介紹MediaPlayer本地音樂播放器,而當應用程式不再位於前台且沒有正在使用它的活動時,為了確保音頻繼續播放,我們需要建立一個服務Service。

Activity與綁定服務Service之間的互動是本文章的重點(這裡需要說明一點的是,Activity不能直接存取服務物件中的方法,所以才有了我們一下的介紹,這也是為服務的安全等方面的考慮)。


直接上代碼:

布局檔案:activity_main:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_horizontal"        android:text="開啟後台服務播放音頻" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal"         android:layout_marginTop="50dp">        <Button            android:id="@+id/fastBackward"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="快退" />        <Button            android:id="@+id/startServiceButton"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="開啟" />        <Button            android:id="@+id/stopServiceButton"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="關閉" />        <Button            android:id="@+id/fastForward"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="快進" />    </LinearLayout></LinearLayout>

MainActivity:

package com.multimediademo6audioservice;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private Button startServiceButton, stopServiceButton, fastBackward,fastForward;private Intent intentService;private SimpleAudioService simpleAudioService;boolean flag = false;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}/** * 執行個體化組件 */private void init() {startServiceButton = (Button) findViewById(R.id.startServiceButton);stopServiceButton = (Button) findViewById(R.id.stopServiceButton);fastBackward = (Button) findViewById(R.id.fastBackward);fastForward = (Button) findViewById(R.id.fastForward);startServiceButton.setOnClickListener(this);stopServiceButton.setOnClickListener(this);fastBackward.setOnClickListener(this);fastForward.setOnClickListener(this);intentService = new Intent(this, SimpleAudioService.class);}@Overridepublic void onClick(View v) {switch (v.getId()) {/*** * 開啟 */case R.id.startServiceButton:startService(intentService);/** * 通過一條bindService命令建立了與服務的串連,且該bindService命令把這個對象( * 下面的ServiceConnection介面)命名為serviceConnection。 */bindService(intentService, serviceConnection,Context.BIND_AUTO_CREATE);flag = true;break;/** * 關閉 */case R.id.stopServiceButton:if (flag) {unbindService(serviceConnection);stopService(intentService);flag = false;}break;/** * 快退 */case R.id.fastBackward:if (flag) {simpleAudioService.backwardFun();}break;/** * 快進 */case R.id.fastForward:if (flag) {simpleAudioService.forwardFun();}break;default:break;}}/** * serviceConnection是一個ServiceConnection類型的對象,它是一個介面,用於監聽所綁定服務的狀態 */private ServiceConnection serviceConnection = new ServiceConnection() {/** * 點擊開啟按鈕,會調用serviceConnection對象中的onServiceConnected方法。 * 向該方法傳遞一個IBinder對象 * ,其實際是從服務本身建立和提交的。這個IBinder對象將是SimpleAudioServiceBinder類型,我們將在服務中建立它。 * 它將有一個方法用於返回我們的服務本身,成為getService,這樣我們就可以對該方法返回的對象直接進行操作。 */@Overridepublic void onServiceConnected(ComponentName name, IBinder sasBinder) {simpleAudioService = ((SimpleAudioService.SimpleAudioServiceBinder) sasBinder).getService();}/** * 該方法用於處理與服務中斷連線時的情況。 */@Overridepublic void onServiceDisconnected(ComponentName name) {simpleAudioService = null;}};}

開啟的服務類:SimpleAudioService:

package com.multimediademo6audioservice;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.media.MediaPlayer.OnCompletionListener;import android.os.Binder;import android.os.IBinder;import android.util.Log;/** * 開啟的服務 * */public class SimpleAudioService extends Service implements OnCompletionListener {private String TAG = "zhongyao";private MediaPlayer player;public class SimpleAudioServiceBinder extends Binder {SimpleAudioService getService() {return SimpleAudioService.this;}}private final IBinder sasBinder = new SimpleAudioServiceBinder();@Overridepublic IBinder onBind(Intent intent) {return sasBinder;}/** * 在MainActivity中點擊開啟後調用startService開啟服務時, * 會調用如下的兩個方法:onCreate(),onStartCommand() */@Overridepublic void onCreate() {super.onCreate();Log.v(TAG, "onCreate");player = MediaPlayer.create(this, R.raw.good);player.setOnCompletionListener(this);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d(TAG, "onStartCommand");if (!player.isPlaying()) {player.start();}return super.onStartCommand(intent, flags, startId);}/** * 調用stopService停止服務時,會調用onDestroy()方法。 */@Overridepublic void onDestroy() {super.onDestroy();Log.d(TAG, "onDestroy");if (player.isPlaying()) {player.stop();}player.release();}/** * 播放完以後調用 */@Overridepublic void onCompletion(MediaPlayer mp) {stopSelf();}/** * 服務中方法:快退 */public void backwardFun() {if (player.isPlaying()) {player.seekTo(player.getCurrentPosition() - 2500);}}/** * 服務中方法:快進 */public void forwardFun() {if (player.isPlaying()) {player.seekTo(player.getCurrentPosition() + 2500);}}}

源碼下載:

點擊下載源碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.