一、Service介紹
Service類似於Windows中的服務,沒有介面,只是在後台運行;而服務不能自己運行,而是需要調用Context.startService(Intent intent);或Context.bindService(Intent intent)開啟服務;
服務分為兩種:
(1)訪問者與服務無關,則關閉訪問者之後,服務能夠繼續運行,使用startService();
(2)訪問者與服務有關(比如訪問者需要調用服務提供的方法),則關閉訪問者後,服務也要關閉,使用bindService();
服務分為:
(1)本地服務:訪問者和服務在一個應用中;
(2)遠程服務:訪問者和服務在不同應用者;
註:如果我們想讓服務開機自動運行,則可以建立一個廣播接收者,並在onReceive中調用開啟服務代碼;
我們這裡只介紹“訪問者與服務無關”的情況,以後再講另一種情況;
二、Service核心代碼
(1)建立繼承Service的類
(2)在AndroidManifest.xml中配置<service>
(3)覆寫Service中onCreate();方法
開始服務:
Intent service = new Intent(Context,XxxService.class);
Context.startService(service);
然後會調用onCreate()方法;
停止服務:
Intent service = new Intent(Context,XxxService.class);
Context.stopService(service);
然後會調用onDestroy()方法;
三、Service生命週期
1.通過Context.startService()啟動服務
onCreate()-->onStart()-->onDestroy()
onCreate()在建立服務時調用,如果調用多次startService(),onCreate()方法仍然只被調用一次;
onStart()在開始startService()調用時被調用,多次startService(),onStart()方法會被調用多次;
onDestroy()在終止服務時調用;
2.通過Context.bindService()啟動服務
onCreate()-->onBind()-->onUnbind()-->onDestroy()
onBind()在綁定服務時調用,如果調用多次bindService(),則onBind()方法只被調用一次;
onUnbind()在解除綁定(unBindService)時調用;
四、MediaPlayer核心代碼
Mediaplayer player = MediaPlayer.create(getApplicationContext(), R.raw.xiazdong);//建立MediaPlayer對象
player.setLooping(true);//迴圈播放
player.start(); //開始播放
player.stop();//停止播放
player.release();//釋放資源
四、將MP3播放應用於Service
此處只是實現點擊Activity的播放音樂,則開始播放音樂,播放音樂的代碼放到Service中,因此就算關閉應用,音樂也不會停止;
效果如下:
MainActivity中點擊按鈕後執行下面代碼:
private OnClickListener listener = new OnClickListener(){@Overridepublic void onClick(View v) {if(v==button){Intent service = new Intent(MainActivity.this,MediaPlayerService.class);MainActivity.this.startService(service);//開啟服務}if(v==button2){Intent name = new Intent(MainActivity.this,MediaPlayerService.class);MainActivity.this.stopService(name);//停止服務}}};
MediaPlayerService.java
package com.xiazdong.mediaplayer;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;public class MediaPlayerService extends Service {private MediaPlayer player;@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {super.onCreate();player = MediaPlayer.create(getApplicationContext(), R.raw.xiazdong);player.setLooping(true);try {//因為MediaPlayer的create已經調用了prepare方法,因此此處直接start方法即可player.start(); } catch (Exception e) {e.printStackTrace();} }@Overridepublic void onDestroy() {//停止服務super.onDestroy();if(player!=null){player.stop();player.release();player = null;}}}
在AndroidManifest.xml中添加:
<service android:name=".MediaPlayerService"/>