天天看點

筆記——BindService實作音樂播放

先建立一個moudle,在res檔案夾中建立raw檔案夾,将音樂檔案存放到raw中。 1.在布局檔案中添加三個按鈕,播放,暫停,停止。

筆記——BindService實作音樂播放
筆記——BindService實作音樂播放
筆記——BindService實作音樂播放

2.在java檔案中執行個體化,并添加監聽

筆記——BindService實作音樂播放
筆記——BindService實作音樂播放
筆記——BindService實作音樂播放

3.建立BindService.java檔案,并繼承自Service,在自定義内部類中,寫一個方法,方法中有一個指派操作,把參數清單中的值指派給Service目前類的值,并把onBind的傳回值改為建立的方法; 代碼如下: public class BindService extends Service{ private MediaPlayer mMediaPlayer; @Nullable @Override public IBinder onBind(Intent intent) { return new MyMusic(); } public class MyMusic extends Binder{ public void play(){ mMediaPlayer.start(); } public void pauser(){ mMediaPlayer.pause(); } public void stop(){ mMediaPlayer.stop(); mMediaPlayer =MediaPlayer.create(BindService.this,R.raw.huanlezhongguonian); } }

@Override public void onCreate() { super.onCreate(); mMediaPlayer = MediaPlayer.create(this,R.raw.huanlezhongguonian); }

@Override public void onDestroy() { super.onDestroy(); mMediaPlayer.release(); } } 4.在主類中,執行個體化MyMusic,.在serviceConnection方法中,實作指派操作,即自定義好的類的變量名=iBinder,然後強制類型轉換

筆記——BindService實作音樂播放
筆記——BindService實作音樂播放
筆記——BindService實作音樂播放

5.在初始化方法中執行個體化Intent,選擇跳轉到哪個頁面,啟動bindService服務。

筆記——BindService實作音樂播放
筆記——BindService實作音樂播放
筆記——BindService實作音樂播放

6.按鈕監聽的動作:

筆記——BindService實作音樂播放
筆記——BindService實作音樂播放
筆記——BindService實作音樂播放

7.在最後添加onDestory,從線程結束bindService;

筆記——BindService實作音樂播放
筆記——BindService實作音樂播放

MainActivity.java代碼: public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button btn_start,btn_pause,btn_stop; private BindService.MyMusic mMyMusic; ServiceConnection conn=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mMyMusic= (BindService.MyMusic) service; }

@Override public void onServiceDisconnected(ComponentName name) {

} };

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent =new Intent(); intent.setClass(this,BindService.class); bindService(intent,conn,BIND_AUTO_CREATE); initView(); } private void initView() { btn_start = (Button) findViewById(R.id.button); btn_pause = (Button) findViewById(R.id.button2); btn_stop = (Button) findViewById(R.id.button3); btn_start.setOnClickListener(this); btn_pause.setOnClickListener(this); btn_stop.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: if(mMyMusic!=null){ mMyMusic.play(); } break; case R.id.button2: if(mMyMusic!=null){ mMyMusic.pause(); } break; case R.id.button3: if(mMyMusic!=null){ mMyMusic.stop(); } break; } }

@Override protected void onDestroy() { super.onDestroy(); unbindService(conn); } } 8.在清單檔案中添加service權限 <service android:name=".BindService"/>

筆記——BindService實作音樂播放
筆記——BindService實作音樂播放