Service啟動模式
Service簡介
Service表示服務,是Android系統的核心組件之一。
Service的本質是一個繼承了android.app.Service的java類;
每一個Service都應該在AndroidMainfest.xml檔案中進行註冊;
Service由Android系統進行維護。
Service沒有匹配的使用者介面,通常用於幕後處理耗時操作。
不允許在主線程中執行耗時操作。
Service是運行在主線程中的;
儘管Service被定位為“用於處理耗時操作”,但是各種耗時操作需要在Service中另外開闢線程來完成。
組件可以綁定到Service,實現處理序間通訊(Inter Process Communication)。
進程優先順序:
Android系統力圖維護儘可能多的線程,但由於裝置效能有限,在動態管理記憶體的過程中,Android系統
會經常能夠終止一些優先順序低的進程,以釋放資源,保證優先順序高的進程正常運行。
進程優先順序分類:
1、前台進程(Forground Process)
2、可見進程(Visible Process)
3、服務進程(Service Process)
4、後台進程(BackGround Process)
5、空進程(Empty Process)
啟動Service
開發人員可以使用Intent啟用Service組件。
啟用Service組件的方式有:
調用Context定義的startService()方法(啟動)
調用Context定義的bindService()方法(綁定)
啟動Service的開發流程
啟動Service的開發流程如下:
1、建立java類,繼承android.app.Service;(Service中定義了抽象方法onBlind(),該方法必須被重寫,但不一定需要被具體實現)
2、在AndroidMainfest.xml中的下添加子節點,
配置建立的Service;
3、在Activity中調用startService(Intent intent)方法啟動Service;
顯式或隱式啟動Service
無論是顯式Intent或隱式Intent都可以啟用Service組件。
如果需要實現處理序間通訊,則應該為Service組件配置隱式意圖過濾器。
停止Service
通過調用Context的stopService(Intent intent)方法可以停止Service,並銷毀該Service組件。
在Service中調用stopSelf()方法可以停止自身。
Service的生命週期
如果Activity反覆調用startService()方法,在Service中只會反覆調用onStartCommand()方法。
案例:
<Button android:id="@+id/btn_start" android:layout_width="match_parent" android:layout_height="wrap_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:onClick="doStart" android:text="Start Service"/> <Button android:layout_marginTop="20dp" android:id="@+id/btn_stop" android:layout_width="match_parent" android:layout_height="wrap_parent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:onClick="doStop" android:text="Start Service"/>
public void doStart(View view){ Intent intent = new Intent(this,SampleService.class); startService(intent);}public void doStop(View view){ Intent intent = new Intent(this,SampleService.class); stopService(intent);}
Service類:
public class SampleService exteds Service{ public void onCreate(){ Log.d(tag,"onCreate") super.onCreate(); } public int onStartCommand(Intent intent,int flags,int startId){ Log.d(tag,"onStartCommand"); return super.onStartCommand(intent,flags,startId); } public void onDestroy(){ Log.d(tag,"onDestroy"); super.onDestroy(); } }AndroidMainfest.xml
Service的粘性
Service的粘性:Service的粘性表現為其所在進程被意外中止後,該Service是否可以自動重新被啟動。
預設情況下,使用startService()方式啟用的Service組件是粘性的,則即使其所在進程被意外中止了,
稍後該Service依然會被自動建立出來。
設定Service的粘性
在Service生命週期中onStartCommand()方法的傳回值決定了Service的粘性。
該方法的傳回值可以被設定為:
START_STICKY:粘性的,被意外中止後自動重啟,但丟失原來用於啟用它的Intent;
START_NOT_STICKY:非粘性的,被意外中止後不會自動重啟;
START_REDELIVER_INTENT:粘性的且重新發送Intent,即被意外中止後自動重啟,且該Service
組件將得到原來用於啟用它的Intent對象;
START_STICKY_COMPATIBILITY:START_STICKY的相容版本,並不擔保onStartCommand()會被重新調用。
案例:
Service播放音樂
使用系統的MediaPlayer類可以播放音樂,開發步驟如下:
建立MediaPlayer對象,可直接使用無參數構造方法;
調用MediaPlaye的reset()方法重設(不必要);
調用MediaPlayer的setDataSource()方法設定需要播放的歌曲;
調用MediaPlayer的prepare()方法載入(緩衝)歌曲;
調用MediaPlayer的start()方法播放歌曲;
當退出時應該調用release()方法釋放資源。
本例的商務邏輯:
通過Activity啟用Service,且在Service中建立mediaPlayer的執行個體,實現歌曲的播放;
被播放的歌曲儲存在模擬器的sdcard/Misic/中;
當Activity被停止時,停止播放歌曲的Service;
當Service被停止時,釋放MediaPlayer的資源。
案例:
MainActivity:
package com.edu.hpu.service;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void startMusic(View view){Intent intent = new Intent(this,PlayerMusicService.class);startService(intent);}@Overrideprotected void onDestroy() {// TODO Auto-generated method stubIntent intent = new Intent(this,PlayerMusicService.class);stopService(intent);super.onDestroy();}}布局:
<RelativeLayout 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" > <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="136dp" android:onClick="startMusic" android:text="播放音樂" /> </RelativeLayout>
Service類:
package com.edu.hpu.service;import java.io.IOException;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.Environment;import android.os.IBinder;public class PlayerMusicService extends Service{ private MediaPlayer player; @Overridepublic void onCreate() { try { player = new MediaPlayer(); player.reset(); player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/Groove Coverage - She.mp3"); player.prepare(); player.start();} catch (IllegalArgumentException e) {// TODO: handle exceptione.printStackTrace();}catch(SecurityException e){e.printStackTrace();} catch(IllegalStateException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); }}@Overridepublic void onDestroy() {// TODO Auto-generated method stubplayer.release();player = null;super.onDestroy();}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}
配置:
關於MediaPlayer MediaPlayer支援主流的音頻、視頻檔案的播放,亦支援播放 非原生媒體檔案; MediaPlayer會開啟子線程播放歌曲; 可調用pause()方法暫停播放,調用seekTo()方法快進到指定的 位置開始播放; 可調用prepareAsync()方法載入歌曲,並配置OnPreparedListener, 在監聽器用調用MediaPlayer的start()方法; 通常為MediaPlayer配置OnCompletionListener,以實現在播放完成後的處理