当前位置:网站首页>android studio AIDL的使用
android studio AIDL的使用
2020-11-09 12:12:00 【osc_252iaxru】
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();
3.反思与总结
1.
2.
3.
4.
5.
6.
版权声明
本文为[osc_252iaxru]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4392850/blog/4709330
边栏推荐
- Gather in Beijing! Openi / O 2020 Qizhi Developer Conference enters countdown
- vscode 插件配置指北
- 深圳C1考证历程
- 在嵌入式设备中实现webrtc的第三种方式③
- Chrome browser engine blink & V8
- AI应届生年薪涨到40万了,你现在转行还来得及!
- Recommended tools for Mac
- A simple way to realize terminal text paste board
- Kubernetes business log collection and monitoring
- After SQL group query, get the first n records of each group
猜你喜欢
el-table动态表头
Understanding task and async await
Android check box and echo
Recommendation system, in-depth paper analysis gbdt + LR
TiDB x 微众银行 | 耗时降低 58%,分布式架构助力实现普惠金融
走进京东 | 中国空间技术研究院青年创新联盟成员莅临参观京东总部
050_ object-oriented
Introduction to zero based im development (4): what is message timing consistency in IM systems?
Visual Studio (MAC) installation process notes
一个简单的能力,决定你是否会学习!
随机推荐
基于synchronized锁的深度解析
Chrome浏览器引擎 Blink & V8
Python zero basics tutorial (01)
财富自由梦缓?蚂蚁金服暂停上市,监管后估值或下跌
The history of C1 research in Shenzhen
Recommended tools for Mac
A simple way to realize terminal text paste board
百亿级数据分表后怎么分页查询?
分库分表的 9种分布式主键ID 生成方案,挺全乎的
Mac 必备优质工具推荐
Introduction to zero based im development (4): what is message timing consistency in IM systems?
Visual Studio (MAC) installation process notes
Using stream to read and write files to process large files
For and for... In, for each and map and for of
The third way to realize webrtc in embedded devices
Handwritten digital image recognition convolution neural network
在企业的降本增效诉求下,Cube如何助力科盾业务容器化“一步到位”?
外贸自建网站域名的选择— Namesilo 域名购买
零基础IM开发入门(四):什么是IM系统的消息时序一致性?
Depth analysis based on synchronized lock