008 Android之Service
文章目錄
- 服務概述
- 服務的兩種啟動方式
- 服務的生命周期
- startService
- startService實例1
- startService實例---電話監聽器
- startService實例---計時器
- bindService
- bindService實例---本地人員查詢系統
服務概述
服務Serivce是Android系統中4大組件之一,有以下特點
基本使用步驟:
服務的兩種啟動方式
服務有兩種啟動方式
startService方式
- 該方法啟動的服務所在的進程屬于服務進程
- Activity一旦啟動服務,服務就跟Activity無關
bindService方式
- 該方法啟動的服務所在進程不屬于服務進程
- Activity與服務建立連接,Activity退出,服務也退出
服務的生命周期
如果Service還沒有運行,則Android先調用onCreate()方法,然后調用onStartCommad(),如果Service已經運行,則只調用onStartCommad()方法,所以一個Service的onStartCommad方法可能會調用多次
startService
startService實例1
xml界面代碼如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn1"android:onClick="btnStart1"android:text="start啟動服務"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn2"android:onClick="btnStop1"android:text="start關閉服務"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>新建兩個按鈕,并創建onClick事件
然后新建一個服務
@Overridepublic void onCreate() {super.onCreate();Log.d("GuiShou","MyService onCreate");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d("GuiShou","MyService onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();Log.d("GuiShou","MyService onDestroy");}重寫onCreate onStartCommand和onDestroy三個方法
public void btnStart1(View view) {//創建IntentIntent intent=new Intent();//設置信息intent.setClass(this,MyService.class);//啟動服務startService(intent);}public void btnStop1(View view) {//創建IntentIntent intent=new Intent();//設置信息intent.setClass(this,MyService.class);//關閉服務stopService(intent);}最后完成創建服務和關閉服務的代碼。
實際效果如圖
點擊啟動服務,會調用onCreate和onStartCommand方法
再次點擊啟動服務,會調用onStartCommand方法
點擊關閉服務,則調用onDestroy方法
startService實例—電話監聽器
原理:在創建服務時獲取電話管理器,注冊監聽器監聽電話狀態。這里基于上面的代碼來完成這個實例。
public class MyPhoneListener extends PhoneStateListener{@Overridepublic void onCallStateChanged(int state, String incomingNumber) {super.onCallStateChanged(state, incomingNumber);switch (state){case TelephonyManager.CALL_STATE_IDLE:Log.d("GuiShou","MyService 電話空閑");break;case TelephonyManager.CALL_STATE_OFFHOOK:Log.d("GuiShou","MyService 電話接聽");break;case TelephonyManager.CALL_STATE_RINGING:Log.d("GuiShou","MyService 電話響鈴");break;}}}首先編寫一個自己的電話監聽類
private TelephonyManager mTelephonyManager;private MyPhoneListener mMyPhoneListener;接著定義兩個成員變量
@Overridepublic void onCreate() {super.onCreate();Log.d("GuiShou","MyService onCreate");//獲取電話管理器mTelephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);//創建監聽器mMyPhoneListener=new MyPhoneListener();//開始監聽打電話狀態mTelephonyManager.listen(mMyPhoneListener,PhoneStateListener.LISTEN_CALL_STATE);}重寫onCreate方法,開始監聽電話狀態
@Overridepublic void onDestroy() {super.onDestroy();Log.d("GuiShou","MyService onDestroy");//取消監聽mTelephonyManager.listen(mMyPhoneListener,PhoneStateListener.LISTEN_NONE);}然后在onDestroy方法中取消監聽
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>然后在清單文件中添加讀取電話狀態的權限
startService實例—計時器
原理:在創建服務時在onCreate方法中啟動定時器,定時發送廣播。在創建Activity時注冊廣播接收者,接收時間廣播,更新控件
首先新建一個服務,命名為TimerService
private Timer mTimer; private int mCount=0; private String mShouText="當前計時:0";創建三個變量
@Overridepublic void onCreate() {super.onCreate();//創建定時器mTimer=new Timer();//創建定時器任務TimerTask timerTask=new TimerTask() {@Overridepublic void run() {mCount++;Log.d("GuiShou",mShouText+mCount);}};//給定時器指定定時器任務mTimer.schedule(timerTask,0,1000);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {mCount=0; //重置return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();//取消定時器if (mTimer!=null){mTimer.cancel();mTimer=null;}}然后完成onCreate onStartCommand和onDestroy方法
<Buttonandroid:id="@+id/btn3"android:onClick="btnStart2"android:text="start啟動服務-計時器"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn4"android:onClick="btnStop2"android:text="start關閉服務-計時器"android:layout_width="match_parent"android:layout_height="wrap_content" />在界面文件中新增兩個按鈕,并添加onClick方法
public void btnStart2(View view) {//創建IntentIntent intent=new Intent();//設置信息intent.setClass(this,TimerService.class);//啟動服務startService(intent);}public void btnStop2(View view) {//創建IntentIntent intent=new Intent();//設置信息intent.setClass(this,TimerService.class);//關閉服務stopService(intent);}啟動服務和關閉服務代碼和之前相同,只需要修改服務名
實際效果如圖:
啟動服務后,定時器開始自動計時
bindService
綁定方式(bindService)
- 通過服務鏈接(Connection)或直接獲取Service中的狀態和數據
- 服務鏈接能夠獲取Service的對象,因此綁定Service的組件可以調用Service中的實現函數
- 使用Service的組件通過Context.bindService()建立服務鏈接,通過Context.unbindService()停止服務鏈接
- 如果在綁定過程中Service沒有啟動,Context.bindService()會自動啟動服務
- 同一個Service可以綁定多個服務鏈接,這樣可以同時為多個不同的組件提供服務
bindService實例—本地人員查詢系統
首先編寫界面代碼
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:orientation="vertical"android:layout_height="match_parent"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn1"android:onClick="btnBind"android:text="綁定服務"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn2"android:onClick="btnUnBind"android:text="解綁服務"android:layout_width="match_parent"android:layout_height="wrap_content" /><EditTextandroid:id="@+id/edit_query"android:hint="請在此輸入ID"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn3"android:onClick="btnQuery"android:text="查詢"android:layout_width="match_parent"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/tv1"android:text="當前數據:"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>新建一個服務,命名為BindService
新建一個接口,命名為IPersonListener
public interface IPersonListener {String queryNameById(int id); }在接口中聲明queryNameById方法
String names[]={"齊天大圣","豬八戒","沙和尚","白龍馬"};public class MyBinder extends Binder implements IPersonListener{@Overridepublic String queryNameById(int id) {if (id<0&&id>3){return "唐僧";}return names[id];}}在服務中編寫一個內部類,實現IPersonListener接口,完成查詢方法
public MyBinder mMyBinder;@Overridepublic IBinder onBind(Intent intent) {Log.d("GuiShou","MyBindService::onBind");// TODO: Return the communication channel to the service.return mMyBinder;}@Overridepublic void onCreate() {super.onCreate();mMyBinder=new MyBinder();Log.d("GuiShou","MyBindService::onCreate");}然后定義類對象,在onCreate方法中新建對象,在onBind中返回對象
public class MyServiceConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {}@Overridepublic void onServiceDisconnected(ComponentName componentName) {}}private MyServiceConnection mMyServiceConnection;在MainActivity中創建一個內部類,并實現ServiceConnection接口;然后定義類對象
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mMyServiceConnection=new MyServiceConnection();}并且在onCreate方法中對類對象進行初始化
public void btnBind(View view) {Intent intent=new Intent(this,BindService.class);bindService(intent,mMyServiceConnection,Context.BIND_AUTO_CREATE);}public void btnUnBind(View view) {Intent intent=new Intent(this,BindService.class);unbindService(mMyServiceConnection);stopService(intent);}完成按鈕響應事件的綁定和解綁服務代碼
private BindService.MyBinder mMyBinder;然后定義一個MyBinder對象
public class MyServiceConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {Log.d("GuiShou","MyBindService::onServiceConnected");mMyBinder= (BindService.MyBinder) iBinder;}然后在onServiceConnected方法中去獲取MyBinder的類對象
public void btnQuery(View view) {EditText editText=findViewById(R.id.edit_query);String string=editText.getText().toString();int num=Integer.parseInt(string);if (mMyBinder!=null){String name=mMyBinder.queryNameById(num);TextView textView=findViewById(R.id.tv1);textView.setText(name);}}最后完成查詢函數。實際效果如圖
總結
以上是生活随笔為你收集整理的008 Android之Service的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 007 Android之Broadcas
- 下一篇: 009 Android之ContentP