1.全部代码
参考视频:视频连接
1.MainActivity
package com.kunminx.aidlmukewangtest;
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.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mBtConnect;
private Button mBtDisConnect;
private Button mBtIsConnected;
private IConnectionService mConnectionService;
private boolean connection=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
Intent mIntent = new Intent(this, RemoteService.class);
bindService(mIntent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//初始化aidl创建的接口
mConnectionService = IConnectionService.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}, BIND_AUTO_CREATE);
}
private void initView() {
mBtConnect = (Button) findViewById(R.id.bt_connect);
mBtDisConnect = (Button) findViewById(R.id.bt_disConnect);
mBtIsConnected = (Button) findViewById(R.id.bt_isConnected);
mBtConnect.setOnClickListener(this);
mBtDisConnect.setOnClickListener(this);
mBtIsConnected.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_connect:
//连接
try {
mConnectionService.connect();
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.bt_disConnect:
//断开
try {
mConnectionService.disconnect();
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.bt_isConnected:
try {
connection = mConnectionService.isConnection();
} catch (RemoteException e) {
e.printStackTrace();
}
Toast.makeText(this, String.valueOf(connection), Toast.LENGTH_SHORT).show();
break;
}
}
}
2.RemoteService
package com.kunminx.aidlmukewangtest;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.widget.Toast;
public class RemoteService extends Service {
public RemoteService() {
}
//设置远程服务状态,默认为false(不连接)
private boolean isConnected=false;
//下面三个方法都是在新进程里的子线程中进行的,所以Toast要用handle来进行线程通讯
private Handler handler=new Handler(Looper.getMainLooper());
private IConnectionService connectionService=new IConnectionService.Stub() {
@Override
public void connect() throws RemoteException {
//模拟新进程耗时操作
try {
Thread.sleep(3000);
isConnected=true;
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(RemoteService.this, "connect", Toast.LENGTH_SHORT).show();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void disconnect() throws RemoteException {
isConnected=false;
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(RemoteService.this, "disConnect", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean isConnection() throws RemoteException {
//获取连接状态
return isConnected;
}
};
@Override
public IBinder onBind(Intent intent) {
return connectionService.asBinder();
}
}
3.IConnectionService.aidl
// IConnectionService.aidl
package com.kunminx.aidlmukewangtest;
// 连接服务
interface IConnectionService {
void connect();//连接
void disconnect();//断开连接
boolean isConnection();//获取连接状态
}
4.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kunminx.aidlmukewangtest">
<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=".RemoteService"
android:enabled="true"
android:exported="true"
android:process=":remote"></service>
</application>
</manifest>
5.activity_main.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"
android:orientation="vertical">
<Button
android:id="@+id/bt_connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="connect" />
<Button
android:id="@+id/bt_disConnect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="disConnect" />
<Button
android:id="@+id/bt_isConnected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="isConnected" />
</LinearLayout>
2.步骤
1.编写服务类,它是一个新进程的
public class RemoteService extends Service {
public RemoteService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
<service
android:name=".RemoteService"
android:enabled="true"
android:exported="true"
android:process=":remote"></service>
android:process=":remote":运行在新进程里,remote是可以自己命名的
2.MainActivity绑定RemoteServcie
Intent mIntent = new Intent(this, RemoteService.class);
bindService(mIntent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}, BIND_AUTO_CREATE);
3.创建AIDL类
命名为IConnectionService(这个可以自己命名)
然后修改里面的方法:
// IConnectionService.aidl
package com.kunminx.aidlmukewangtest;
// 连接服务
interface IConnectionService {
void connect();//连接
void disconnect();//断开连接
boolean isConnection();//获取连接状态
}
然后编译,他会根据这个AIDL类,创建如下代码
4.生成的代码内容:
BuildConfig :
/**
* Automatically generated file. DO NOT MODIFY
*/
package com.kunminx.aidlmukewangtest;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.kunminx.aidlmukewangtest";
public static final String BUILD_TYPE = "debug";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
IConnectionService :
/*
* This file is auto-generated. DO NOT MODIFY.
*/
package com.kunminx.aidlmukewangtest;
// 连接服务
public interface IConnectionService extends android.os.IInterface
{
/** Default implementation for IConnectionService. */
public static class Default implements com.kunminx.aidlmukewangtest.IConnectionService
{
@Override public void connect() throws android.os.RemoteException
{
}
//连接
@Override public void disconnect() throws android.os.RemoteException
{
}
//断开连接
@Override public boolean isConnection() throws android.os.RemoteException
{
return false;
}
@Override
public android.os.IBinder asBinder() {
return null;
}
}
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.kunminx.aidlmukewangtest.IConnectionService
{
private static final java.lang.String DESCRIPTOR = "com.kunminx.aidlmukewangtest.IConnectionService";
/** Construct the stub at attach it to the interface. */
public Stub()
{
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.kunminx.aidlmukewangtest.IConnectionService interface,
* generating a proxy if needed.
*/
public static com.kunminx.aidlmukewangtest.IConnectionService asInterface(android.os.IBinder obj)
{
if ((obj==null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin!=null)&&(iin instanceof com.kunminx.aidlmukewangtest.IConnectionService))) {
return ((com.kunminx.aidlmukewangtest.IConnectionService)iin);
}
return new com.kunminx.aidlmukewangtest.IConnectionService.Stub.Proxy(obj);
}
@Override public android.os.IBinder asBinder()
{
return this;
}
@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
{
java.lang.String descriptor = DESCRIPTOR;
switch (code)
{
case INTERFACE_TRANSACTION:
{
reply.writeString(descriptor);
return true;
}
case TRANSACTION_connect:
{
data.enforceInterface(descriptor);
this.connect();
reply.writeNoException();
return true;
}
case TRANSACTION_disconnect:
{
data.enforceInterface(descriptor);
this.disconnect();
reply.writeNoException();
return true;
}
case TRANSACTION_isConnection:
{
data.enforceInterface(descriptor);
boolean _result = this.isConnection();
reply.writeNoException();
reply.writeInt(((_result)?(1):(0)));
return true;
}
default:
{
return super.onTransact(code, data, reply, flags);
}
}
}
private static class Proxy implements com.kunminx.aidlmukewangtest.IConnectionService
{
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote)
{
mRemote = remote;
}
@Override public android.os.IBinder asBinder()
{
return mRemote;
}
public java.lang.String getInterfaceDescriptor()
{
return DESCRIPTOR;
}
@Override public void connect() throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
boolean _status = mRemote.transact(Stub.TRANSACTION_connect, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
getDefaultImpl().connect();
return;
}
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
//连接
@Override public void disconnect() throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
boolean _status = mRemote.transact(Stub.TRANSACTION_disconnect, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
getDefaultImpl().disconnect();
return;
}
_reply.readException();
}
finally {
_reply.recycle();
_data.recycle();
}
}
//断开连接
@Override public boolean isConnection() throws android.os.RemoteException
{
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
boolean _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
boolean _status = mRemote.transact(Stub.TRANSACTION_isConnection, _data, _reply, 0);
if (!_status && getDefaultImpl() != null) {
return getDefaultImpl().isConnection();
}
_reply.readException();
_result = (0!=_reply.readInt());
}
finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
public static com.kunminx.aidlmukewangtest.IConnectionService sDefaultImpl;
}
static final int TRANSACTION_connect = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_disconnect = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_isConnection = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
public static boolean setDefaultImpl(com.kunminx.aidlmukewangtest.IConnectionService impl) {
// Only one user of this interface can use this function
// at a time. This is a heuristic to detect if two different
// users in the same process use this function.
if (Stub.Proxy.sDefaultImpl != null) {
throw new IllegalStateException("setDefaultImpl() called twice");
}
if (impl != null) {
Stub.Proxy.sDefaultImpl = impl;
return true;
}
return false;
}
public static com.kunminx.aidlmukewangtest.IConnectionService getDefaultImpl() {
return Stub.Proxy.sDefaultImpl;
}
}
public void connect() throws android.os.RemoteException;
//连接
public void disconnect() throws android.os.RemoteException;
//断开连接
public boolean isConnection() throws android.os.RemoteException;
}
5.在RemoteService编写代码
实现aidl代码
//设置远程服务状态,默认为false(不连接)
private boolean isConnected=false;
//下面三个方法都是在新进程里的子线程中进行的,所以Toast要用handle来进行线程通讯
private Handler handler=new Handler(Looper.getMainLooper());
private IConnectionService connectionService=new IConnectionService.Stub() {
@Override
public void connect() throws RemoteException {
//模拟新进程耗时操作
try {
Thread.sleep(3000);
isConnected=true;
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(RemoteService.this, "connect", Toast.LENGTH_SHORT).show();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void disconnect() throws RemoteException {
isConnected=false;
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(RemoteService.this, "disConnect", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean isConnection() throws RemoteException {
//获取连接状态
return isConnected;
}
};
返回出去:
@Override
public IBinder onBind(Intent intent) {
return connectionService.asBinder();
}
6.编写MainActivity,实现三按钮:连接,断开连接,获取连接状态,实现监听
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"
android:orientation="vertical">
<Button
android:id="@+id/bt_connect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="connect" />
<Button
android:id="@+id/bt_disConnect"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="disConnect" />
<Button
android:id="@+id/bt_isConnected"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="isConnected" />
</LinearLayout>
快捷方式为按钮初始化与监听
private void initView() {
mBtConnect = (Button) findViewById(R.id.bt_connect);
mBtDisConnect = (Button) findViewById(R.id.bt_disConnect);
mBtIsConnected = (Button) findViewById(R.id.bt_isConnected);
mBtConnect.setOnClickListener(this);
mBtDisConnect.setOnClickListener(this);
mBtIsConnected.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_connect:
break;
case R.id.bt_disConnect:
break;
case R.id.bt_isConnected:
break;
}
}
7.初始化AIDL创建的java类接口
在ServiceConnected的重写方法onServiceConnected中初始化
代码:
//初始化aidl创建的接口
mConnectionService = IConnectionService.Stub.asInterface(service);
8.调用方法:
代码:
连接
//连接
try {
mConnectionService.connect();
} catch (RemoteException e) {
e.printStackTrace();
}
断开连接
//断开
try {
mConnectionService.disconnect();
} catch (RemoteException e) {
e.printStackTrace();
}
获取连接状态:
try {
connection = mConnectionService.isConnection();
} catch (RemoteException e) {
e.printStackTrace();
}
Toast.makeText(this, String.valueOf(connection), Toast.LENGTH_SHORT).show();