詳解Android中Service AIDL的使用
前言
有些朋友可能是從事開發(fā)工作的時間不是特別的長,所以覺得Service相對與另外兩個組件activity、broadcast receiver來說,使用可能并不是特別的多,所以對Service來說,理解不是特別的深入,只是有一個大概的概念,今天就和一塊來走一下Service,希望能夠幫助到大家對Service有更深入的理解。
Service基本用法——本地服務(wù)
我們知道服務(wù)分為本地服務(wù)和遠程服務(wù),而本地服務(wù)由于它的啟動方式不一樣,所以生命周期也就不一樣,對Service生命周期不熟悉的朋友,自行去百度一下啊。好了,那么我們分別看一下兩種不同的啟動方式。
我們先創(chuàng)建好Service:ServiceTest.java
package com.example.administrator.servicetestaidl; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.IntDef; import android.util.Log; public class ServiceTest extends Service { @Override public void onCreate() { super.onCreate(); Log.d("ServiceTest"," -----> onCreate"); } @Override public int onStartCommand(Intent intent,int flags, int startId) { Log.d("ServiceTest"," -----> onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d("ServiceTest"," -----> onDestroy"); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } }
在看看MainActivity的代碼:
package com.example.administrator.servicetestaidl; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private Button startService, stopService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); /** * 開啟服務(wù) */ startService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent startService = new Intent(MainActivity.this,ServiceTest.class); startService(startService); } }); /** * 停止服務(wù) */ stopService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent stopService = new Intent(MainActivity.this,ServiceTest.class); stopService(stopService); } }); } }
布局activity_main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/start_service" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="開啟服務(wù)" /> <Button android:id="@+id/stop_service" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止服務(wù)" /> </LinearLayout>
配置文件AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.administrator.servicetestaidl"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".ServiceTest" android:enabled="true" android:exported="true"></service> </application> </manifest>
上面的代碼很簡單,并不難理解,在頁面上加兩個按鈕,一個是啟動服務(wù),一個是銷毀服務(wù)的,并且我們在ServiceTest里面的幾個方法都加上了log,那我們點擊開啟服務(wù),看看Log,如圖:
然后我們多次點擊開啟服務(wù),如圖:
我們看到,后面即使多點幾下這個開啟服務(wù),但是也只會調(diào)onStartCommand方法,onCreate方法并不會重復(fù)調(diào)用,那是因為我們點擊Service,由于該service已經(jīng)存在,所以并不會重新創(chuàng)建,所以onCreate方法只會調(diào)用一次。
我們還可以到手機的應(yīng)用程序管理界面來檢查一下Service是不是正在運行,如下圖所示:
那當(dāng)我們點擊停止服務(wù)按鈕呢,看看log:如圖
這時候說明了服務(wù)已經(jīng)銷毀了。
有些朋友可能注意到了,我們剛剛那種啟動服務(wù)的方式,好像除了對Service進行開啟和銷毀以外,很難在activity里進行對Service進行控制,什么意思呢?舉個例子,如果說我現(xiàn)在用Service進行下載某些東西,我現(xiàn)在在Service寫有下載這兩個東西的方法,方法a,方法b,那么我怎樣在activity里面控制什么時候調(diào)用方法a,什么時候調(diào)用方法b呢,如果按照原本的啟動方式,好像并不好實現(xiàn),或者說靈活性很差,那么有沒有辦法辦到呢,接著看Service另一種啟動方式。在前面我們有一個方法一直都沒有動onBind方法,我們就從這個方法入手,先看ServiceTest代碼:
package com.example.administrator.servicetestaidl; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.IntDef; import android.util.Log; public class ServiceTest extends Service { @Override public void onCreate() { super.onCreate(); Log.d("ServiceTest"," -----> onCreate"); } @Override public int onStartCommand(Intent intent,int flags, int startId) { Log.d("ServiceTest"," -----> onStartCommand"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d("ServiceTest"," -----> onDestroy"); } @Override public IBinder onBind(Intent intent) { return new Mybind(); } class Mybind extends Binder{ public void getString(){ Log.d("ServiceTest"," -----> getString"); } } }
在ServiceTest中增加了一個內(nèi)部類Mybind,并且在Mybind中增加一個getString方法,在方法中打印log,然后在onBind方法中返回Mybind對象。
再看看MainActivity的代碼
package com.example.administrator.servicetestaidl; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private Button startService,stopService,bindService,unbindService; private ServiceTest.Mybind mybind; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mybind = (ServiceTest.Mybind) service; mybind.getString(); //獲取到getString方法 } @Override public void onServiceDisconnected(ComponentName name) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); bindService = (Button) findViewById(R.id.bind_service); unbindService = (Button) findViewById(R.id.unbind_service); /** * 開啟服務(wù) */ startService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent startService = new Intent(MainActivity.this,ServiceTest.class); startService(startService); } }); /** * 停止服務(wù) */ stopService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent stopService = new Intent(MainActivity.this,ServiceTest.class); stopService(stopService); } }); /** * 綁定服務(wù) */ bindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bindService = new Intent(MainActivity.this,ServiceTest.class); bindService(bindService,connection,BIND_AUTO_CREATE); } }); /** * 解綁服務(wù) */ unbindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { unbindService(connection); } }); } }
主頁面布局:activity_main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/start_service" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="開啟服務(wù)" /> <Button android:id="@+id/stop_service" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="停止服務(wù)" /> <Button android:id="@+id/bind_service" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="綁定服務(wù)" /> <Button android:id="@+id/unbind_service" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="解綁服務(wù)" /> </LinearLayout>
可以看到,這里我們首先創(chuàng)建了一個ServiceConnection的匿名類,在里面重寫了onServiceConnected()方法和onServiceDisconnected()方法,這兩個方法分別會在Activity與Service建立關(guān)聯(lián)和解除關(guān)聯(lián)的時候調(diào)用。在onServiceConnected()方法中,我們又通過向下轉(zhuǎn)型得到了MyBind的實例,有了這個實例,Activity和Service之間的關(guān)系就變得非常緊密了。現(xiàn)在我們可以在Activity中根據(jù)具體的場景來調(diào)用MyBind中的任何public方法,即實現(xiàn)了Activity指揮Service干什么Service就去干什么的功能。
當(dāng)我們點擊綁定服務(wù)的時候,結(jié)果如下,如圖
點擊解綁服務(wù)的時候,結(jié)果如下,如圖
注意:Service 是運行在后臺,沒有可視化的頁面,我們很多時候會把耗時的操作放在Service中執(zhí)行,但是注意,Service是運行在主線程的,不是在子線程中,Service和Thread沒有半毛錢的關(guān)系,所以如果在Service中執(zhí)行耗時操作,一樣是需要開起線程,否則會引起ANR,這個需要區(qū)別開來。
遠程服務(wù) —— AIDL
AIDL(Android Interface Definition Language)是Android接口定義語言的意思,它可以用于讓某個Service與多個應(yīng)用程序組件之間進行跨進程通信,從而可以實現(xiàn)多個應(yīng)用程序共享同一個Service的功能。實際上實現(xiàn)跨進程之間通信的有很多,
比如廣播,Content Provider,但是AIDL的優(yōu)勢在于速度快(系統(tǒng)底層直接是共享內(nèi)存),性能穩(wěn),效率高,一般進程間通信就用它。
既然是跨進程,那必須的有兩個應(yīng)用,一個是service端,一個是client端,然后實現(xiàn)客戶端從服務(wù)端獲取數(shù)據(jù)。那么我們創(chuàng)建一個服務(wù)端,項目結(jié)構(gòu)如圖所示:
服務(wù)端
我們在服務(wù)端下建立一個MyAIDLService.aidl文件,目錄結(jié)構(gòu)為如圖所示:
然后,我們在MyAIDLService下增加一個獲取字符串的方法。代碼如下:(注:剛剛建立的aidl文件中存在一個方法,那個方法可以忽略,可以刪掉不要)
// MyAIDLService.aidl package aidl; // Declare any non-default types here with import statements interface MyAIDLService { //獲取String數(shù)據(jù) String getString(); }
創(chuàng)建完aidl文件以后,我們build一下項目,然后會在build - >generated ->source ->aidl->debug下會生成一個aidl文件,那說明AIDL文件已經(jīng)編譯成功。
接著建立一個MyService類,代碼如下:
package com.example.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.util.Map; import aidl.MyAIDLService; public class MyService extends Service { @Override public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return new Mybind(); } class Mybind extends MyAIDLService.Stub { @Override public String getString() throws RemoteException { String string = "我是從服務(wù)起返回的"; return string; } } }
代碼看起來是不是很熟悉,唯一不一樣的就是原來在本地服務(wù)的時候內(nèi)部類繼承的是Binder,而現(xiàn)在繼承的是MyAIDLService.Stub,繼承的是我們剛剛建立的aidl文件,然后實現(xiàn)我們剛剛的定義的getString()方法,在這里,我們只是返回一句話,"我是從服務(wù)起返回的"~~~~~~~~~~~
客戶端
首先將剛剛在服務(wù)端創(chuàng)建的MyAIDLService原封不動的復(fù)制到客戶端來。(注意:路徑要一模一樣)。接著我們在客戶端的MainActivity中加兩個按鈕,并且和服務(wù)端進行相連,代碼如下:
MainActivity
package com.example.administrator.servicetestaidl; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.view.View; import android.widget.Button; import android.widget.TextView; import aidl.MyAIDLService; public class MainActivity extends Activity { private Button bindService,unbindService; private TextView tvData; private MyAIDLService myAIDLService; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { myAIDLService = MyAIDLService.Stub.asInterface(service); try { String str = myAIDLService.getString(); tvData.setText(str); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { myAIDLService = null; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindService = (Button) findViewById(R.id.bind_service); unbindService = (Button) findViewById(R.id.unbind_service); tvData = (TextView) findViewById(R.id.tv_data); /** * 綁定服務(wù) */ bindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction("com.example.service.MyService"); //從 Android 5.0開始 隱式Intent綁定服務(wù)的方式已不能使用,所以這里需要設(shè)置Service所在服務(wù)端的包名 intent.setPackage("com.example.service"); bindService(intent, connection, BIND_AUTO_CREATE); } }); /** * 解綁服務(wù) */ unbindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { unbindService(connection); } }); } }
大家是不是感覺和連接本地服務(wù)的代碼差不多,沒錯,這里只需要注意兩個地方,一個是綁定服務(wù)的時候,因為從 Android 5.0開始 隱式Intent綁定服務(wù)的方式已不能使用,所以這里需要設(shè)置Service所在服務(wù)端的包名
那么這個action是怎么來的呢,我們回來服務(wù)端的AndroidManifest.xml,代碼如下
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.service"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyService" > <intent-filter> <action android:name="com.example.service.MyService" /> </intent-filter> </service> </application> </manifest>
另一個需要注意的就是獲取MyAIDLService對象是通過MyAIDLService.Stub.asInterface(service);這里大家需要注意一下的。
不過還有一點需要說明的是,由于這是在不同的進程之間傳遞數(shù)據(jù),Android對這類數(shù)據(jù)的格式支持是非常有限的,
基本上只能傳遞Java的基本數(shù)據(jù)類型、字符串、List或Map等。那么如果我想傳遞一個自定義的類該怎么辦呢?這就必須要讓這個類去實現(xiàn)Parcelable接口,并且要給這個類也定義一個同名的AIDL文件。這部分內(nèi)容并不復(fù)雜,而且和Service關(guān)系不大,所以就不再詳細進行講解了,感興趣的朋友可以自己去查閱一下相關(guān)的資料。
注意:從服務(wù)器復(fù)制過來的aidl文件不能直接放到Java文件夾下面,必須建立一個aidl文件夾存放,否則會編譯不成功
好了,到這里,基本上就結(jié)束了,附上一張效果圖:
最后附上源碼鏈接
本地服務(wù)源碼:https://github.com/343661629/nativeService
遠程服務(wù)源碼:https://github.com/343661629/remoteService
以上就是詳解Android中Service AIDL的使用的詳細內(nèi)容,更多關(guān)于Android中Service AIDL的使用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android貝塞爾曲線初步學(xué)習(xí)第二課 仿QQ未讀消息氣泡拖拽黏連效果
這篇文章主要為大家詳細介紹了Android貝塞爾曲線初步學(xué)習(xí)的第二課,仿QQ未讀消息氣泡拖拽黏連效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03ViewPager打造輪播圖Banner/引導(dǎo)頁Guide
這篇文章主要為大家詳細介紹了ViewPager打造輪播圖Banner和引導(dǎo)頁Guide,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08Android使用Intent的Action和Data屬性實現(xiàn)點擊按鈕跳轉(zhuǎn)到撥打電話和發(fā)送短信界面
這篇文章主要介紹了Android中使用Intent的Action和Data屬性實現(xiàn)點擊按鈕跳轉(zhuǎn)到撥打電話和發(fā)送短信,需要的朋友可以參考下2020-01-01Android自定義View之簡約風(fēng)歌詞控件實戰(zhàn)指南
一些接觸Android不久的朋友對自定義View都有一絲畏懼感,總感覺這是一個比較高級的技術(shù),但其實自定義View并不復(fù)雜,有時候只需要簡單幾行代碼就可以完成了,這篇文章主要給大家介紹了關(guān)于Android自定義View之簡約風(fēng)歌詞控件的相關(guān)資料,需要的朋友可以參考下2021-07-07