日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Android >内容正文

Android

008 Android之Service

發(fā)布時(shí)間:2025/3/21 Android 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 008 Android之Service 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

    • 服務(wù)概述
    • 服務(wù)的兩種啟動(dòng)方式
    • 服務(wù)的生命周期
    • startService
      • startService實(shí)例1
      • startService實(shí)例---電話監(jiān)聽(tīng)器
      • startService實(shí)例---計(jì)時(shí)器
    • bindService
      • bindService實(shí)例---本地人員查詢系統(tǒng)

服務(wù)概述

服務(wù)Serivce是Android系統(tǒng)中4大組件之一,有以下特點(diǎn)

  • 后臺(tái)運(yùn)行
  • 沒(méi)有界面
  • 服務(wù)無(wú)法自己?jiǎn)?dòng)
  • 單例模式(一個(gè)服務(wù)在系統(tǒng)中只能啟動(dòng)一次)
  • 基本使用步驟:

  • 繼承自Service
  • 在清單文件中使用節(jié)點(diǎn)配置
  • 啟動(dòng)服務(wù)
  • 服務(wù)的兩種啟動(dòng)方式

    服務(wù)有兩種啟動(dòng)方式

  • startService方式

    • 該方法啟動(dòng)的服務(wù)所在的進(jìn)程屬于服務(wù)進(jìn)程
    • Activity一旦啟動(dòng)服務(wù),服務(wù)就跟Activity無(wú)關(guān)
  • bindService方式

    • 該方法啟動(dòng)的服務(wù)所在進(jìn)程不屬于服務(wù)進(jìn)程
    • Activity與服務(wù)建立連接,Activity退出,服務(wù)也退出
  • 服務(wù)的生命周期

    如果Service還沒(méi)有運(yùn)行,則Android先調(diào)用onCreate()方法,然后調(diào)用onStartCommad(),如果Service已經(jīng)運(yùn)行,則只調(diào)用onStartCommad()方法,所以一個(gè)Service的onStartCommad方法可能會(huì)調(diào)用多次

    startService

    startService實(shí)例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啟動(dòng)服務(wù)"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn2"android:onClick="btnStop1"android:text="start關(guān)閉服務(wù)"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>

    新建兩個(gè)按鈕,并創(chuàng)建onClick事件

    然后新建一個(gè)服務(wù)

    @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");}

    重寫(xiě)onCreate onStartCommand和onDestroy三個(gè)方法

    public void btnStart1(View view) {//創(chuàng)建IntentIntent intent=new Intent();//設(shè)置信息intent.setClass(this,MyService.class);//啟動(dòng)服務(wù)startService(intent);}public void btnStop1(View view) {//創(chuàng)建IntentIntent intent=new Intent();//設(shè)置信息intent.setClass(this,MyService.class);//關(guān)閉服務(wù)stopService(intent);}

    最后完成創(chuàng)建服務(wù)和關(guān)閉服務(wù)的代碼。

    實(shí)際效果如圖

    點(diǎn)擊啟動(dòng)服務(wù),會(huì)調(diào)用onCreate和onStartCommand方法

    再次點(diǎn)擊啟動(dòng)服務(wù),會(huì)調(diào)用onStartCommand方法

    點(diǎn)擊關(guān)閉服務(wù),則調(diào)用onDestroy方法

    startService實(shí)例—電話監(jiān)聽(tīng)器

    原理:在創(chuàng)建服務(wù)時(shí)獲取電話管理器,注冊(cè)監(jiān)聽(tīng)器監(jiān)聽(tīng)電話狀態(tài)。這里基于上面的代碼來(lái)完成這個(gè)實(shí)例。

    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 電話接聽(tīng)");break;case TelephonyManager.CALL_STATE_RINGING:Log.d("GuiShou","MyService 電話響鈴");break;}}}

    首先編寫(xiě)一個(gè)自己的電話監(jiān)聽(tīng)類(lèi)

    private TelephonyManager mTelephonyManager;private MyPhoneListener mMyPhoneListener;

    接著定義兩個(gè)成員變量

    @Overridepublic void onCreate() {super.onCreate();Log.d("GuiShou","MyService onCreate");//獲取電話管理器mTelephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);//創(chuàng)建監(jiān)聽(tīng)器mMyPhoneListener=new MyPhoneListener();//開(kāi)始監(jiān)聽(tīng)打電話狀態(tài)mTelephonyManager.listen(mMyPhoneListener,PhoneStateListener.LISTEN_CALL_STATE);}

    重寫(xiě)onCreate方法,開(kāi)始監(jiān)聽(tīng)電話狀態(tài)

    @Overridepublic void onDestroy() {super.onDestroy();Log.d("GuiShou","MyService onDestroy");//取消監(jiān)聽(tīng)mTelephonyManager.listen(mMyPhoneListener,PhoneStateListener.LISTEN_NONE);}

    然后在onDestroy方法中取消監(jiān)聽(tīng)

    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>

    然后在清單文件中添加讀取電話狀態(tài)的權(quán)限

    startService實(shí)例—計(jì)時(shí)器

    原理:在創(chuàng)建服務(wù)時(shí)在onCreate方法中啟動(dòng)定時(shí)器,定時(shí)發(fā)送廣播。在創(chuàng)建Activity時(shí)注冊(cè)廣播接收者,接收時(shí)間廣播,更新控件

    首先新建一個(gè)服務(wù),命名為T(mén)imerService

    private Timer mTimer; private int mCount=0; private String mShouText="當(dāng)前計(jì)時(shí):0";

    創(chuàng)建三個(gè)變量

    @Overridepublic void onCreate() {super.onCreate();//創(chuàng)建定時(shí)器mTimer=new Timer();//創(chuàng)建定時(shí)器任務(wù)TimerTask timerTask=new TimerTask() {@Overridepublic void run() {mCount++;Log.d("GuiShou",mShouText+mCount);}};//給定時(shí)器指定定時(shí)器任務(wù)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();//取消定時(shí)器if (mTimer!=null){mTimer.cancel();mTimer=null;}}

    然后完成onCreate onStartCommand和onDestroy方法

    <Buttonandroid:id="@+id/btn3"android:onClick="btnStart2"android:text="start啟動(dòng)服務(wù)-計(jì)時(shí)器"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn4"android:onClick="btnStop2"android:text="start關(guān)閉服務(wù)-計(jì)時(shí)器"android:layout_width="match_parent"android:layout_height="wrap_content" />

    在界面文件中新增兩個(gè)按鈕,并添加onClick方法

    public void btnStart2(View view) {//創(chuàng)建IntentIntent intent=new Intent();//設(shè)置信息intent.setClass(this,TimerService.class);//啟動(dòng)服務(wù)startService(intent);}public void btnStop2(View view) {//創(chuàng)建IntentIntent intent=new Intent();//設(shè)置信息intent.setClass(this,TimerService.class);//關(guān)閉服務(wù)stopService(intent);}

    啟動(dòng)服務(wù)和關(guān)閉服務(wù)代碼和之前相同,只需要修改服務(wù)名

    實(shí)際效果如圖:

    啟動(dòng)服務(wù)后,定時(shí)器開(kāi)始自動(dòng)計(jì)時(shí)

    bindService

    綁定方式(bindService)

    • 通過(guò)服務(wù)鏈接(Connection)或直接獲取Service中的狀態(tài)和數(shù)據(jù)
    • 服務(wù)鏈接能夠獲取Service的對(duì)象,因此綁定Service的組件可以調(diào)用Service中的實(shí)現(xiàn)函數(shù)
    • 使用Service的組件通過(guò)Context.bindService()建立服務(wù)鏈接,通過(guò)Context.unbindService()停止服務(wù)鏈接
    • 如果在綁定過(guò)程中Service沒(méi)有啟動(dòng),Context.bindService()會(huì)自動(dòng)啟動(dòng)服務(wù)
    • 同一個(gè)Service可以綁定多個(gè)服務(wù)鏈接,這樣可以同時(shí)為多個(gè)不同的組件提供服務(wù)

    bindService實(shí)例—本地人員查詢系統(tǒng)

    首先編寫(xiě)界面代碼

    <?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="綁定服務(wù)"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn2"android:onClick="btnUnBind"android:text="解綁服務(wù)"android:layout_width="match_parent"android:layout_height="wrap_content" /><EditTextandroid:id="@+id/edit_query"android:hint="請(qǐng)?jiān)诖溯斎隝D"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="當(dāng)前數(shù)據(jù):"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>

    新建一個(gè)服務(wù),命名為BindService

    新建一個(gè)接口,命名為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];}}

    在服務(wù)中編寫(xiě)一個(gè)內(nèi)部類(lèi),實(shí)現(xiàn)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");}

    然后定義類(lèi)對(duì)象,在onCreate方法中新建對(duì)象,在onBind中返回對(duì)象

    public class MyServiceConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {}@Overridepublic void onServiceDisconnected(ComponentName componentName) {}}private MyServiceConnection mMyServiceConnection;

    在MainActivity中創(chuàng)建一個(gè)內(nèi)部類(lèi),并實(shí)現(xiàn)ServiceConnection接口;然后定義類(lèi)對(duì)象

    @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mMyServiceConnection=new MyServiceConnection();}

    并且在onCreate方法中對(duì)類(lèi)對(duì)象進(jìn)行初始化

    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);}

    完成按鈕響應(yīng)事件的綁定和解綁服務(wù)代碼

    private BindService.MyBinder mMyBinder;

    然后定義一個(gè)MyBinder對(duì)象

    public class MyServiceConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {Log.d("GuiShou","MyBindService::onServiceConnected");mMyBinder= (BindService.MyBinder) iBinder;}

    然后在onServiceConnected方法中去獲取MyBinder的類(lèi)對(duì)象

    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);}}

    最后完成查詢函數(shù)。實(shí)際效果如圖

    總結(jié)

    以上是生活随笔為你收集整理的008 Android之Service的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。