先上git的地址
前言:之前在網(wǎng)上找過一些博客學(xué)習(xí)AIDL屯吊,但是很多只有介紹凌彬,但是沒有demo可供參考,或者干脆就做在了一個(gè)APP里面,達(dá)不到兩個(gè)APP間通信的要求收夸,所以就自己整理一下。
1.創(chuàng)建服務(wù)端的app,新建aidl文件,點(diǎn)擊編譯按鈕(如果不編譯會(huì)找不到定義接口生成的Stub抽象類)
1540967210(1).jpg
TIM截圖20181031143248.png
`~ZCISN9ZZO(YIJ]`V}FSNU.png
2.創(chuàng)建一個(gè)server供客戶端調(diào)用,onBind(Intent intent)方法需要返回自定義的AIDL接口
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new IBinderImp(){
@Override
public String str(String str) throws RemoteException {
Log.d("MyService",str);
return super.str(str);
}
};
}
}
public class IBinderImp extends My_Service_Int.Stub {
@Override
public String str(String str) throws RemoteException {
return str;
}
}
//注意 android:exported="true" 砚哆,不然外部無法訪問到
<service
android:name=".MyService"
android:enabled="true"
android:process=":AidlService"
android:exported="true">
<intent-filter>
<action android:name="com.example.kong.myapplication.MyServer" />
</intent-filter>
</service>
3.新建另一個(gè)module(客戶端),拷貝main目錄下的整個(gè)AIDL文件夾到此module下,老規(guī)矩,編譯躁锁,然后編寫代碼綁定服務(wù)端的Service纷铣,需要設(shè)定其action和application的包名
class MainActivity : AppCompatActivity() {
lateinit var my_service_int: My_Service_Int
lateinit var connection: ServiceConnection
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intents = Intent("com.example.kong.myapplication.MyServer")
intents.setPackage("com.example.kong.myapplication")
// intents.component = ComponentName("com.example.kong.myapplication", "com.example.kong.myapplication.MyServer")
connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d("MainActivity", "鏈接上了")
//AIDL接口調(diào)用asInterface(Binder) 獲取到接口對象
my_service_int = My_Service_Int.Stub.asInterface(service)
}
override fun onServiceDisconnected(name: ComponentName) {
}
}
bindService(intents, connection, BIND_AUTO_CREATE)
}
override fun onDestroy() {
super.onDestroy()
unbindService(connection)
}
fun sendMessage(v: View) {
try { //調(diào)用接口中的方法,為其賦值
my_service_int.str("新聞聯(lián)播")
} catch (e: RemoteException) {
e.printStackTrace()
}
}
}
TIM截圖20181031151524.png
接下來就測試服務(wù)有沒有收到消息战转,我點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)點(diǎn)....
TIM截圖20181031151558.png
好的搜立,測試通過,over
本文參考 https://blog.csdn.net/weixin_41317842/article/details/79138291