当前位置:网站首页>The use of Android studio Aidl
The use of Android studio Aidl
2020-11-09 12:12:00 【osc_252iaxru】
1. All the code
Reference video : Video link
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) {
// initialization aidl Created interface
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:
// Connect
try {
mConnectionService.connect();
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.bt_disConnect:
// To break off
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() {
}
// Set remote service status , The default is false( Not connected )
private boolean isConnected=false;
// The following three methods are carried out in the child thread of the new process , therefore Toast Use handle For thread communication
private Handler handler=new Handler(Looper.getMainLooper());
private IConnectionService connectionService=new IConnectionService.Stub() {
@Override
public void connect() throws RemoteException {
// Simulate new process time-consuming operations
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 {
// Get connection status
return isConnected;
}
};
@Override
public IBinder onBind(Intent intent) {
return connectionService.asBinder();
}
}
3.IConnectionService.aidl
// IConnectionService.aidl
package com.kunminx.aidlmukewangtest;
// Connection service
interface IConnectionService {
void connect();// Connect
void disconnect();// disconnect
boolean isConnection();// Get connection status
}
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. step
1. Write a service class , It's a new process
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": Running in a new process ,remote You can name it yourself
2.MainActivity binding 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. establish AIDL class

Name it IConnectionService( This one can be named by itself )
Then modify the method inside :
// IConnectionService.aidl
package com.kunminx.aidlmukewangtest;
// Connection service
interface IConnectionService {
void connect();// Connect
void disconnect();// disconnect
boolean isConnection();// Get connection status
}
Then compile , He'll be based on this AIDL class , Create the following code

4. Generated code content :
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;
// Connection service
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
{
}
// Connect
@Override public void disconnect() throws android.os.RemoteException
{
}
// disconnect
@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();
}
}
// Connect
@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();
}
}
// disconnect
@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;
// Connect
public void disconnect() throws android.os.RemoteException;
// disconnect
public boolean isConnection() throws android.os.RemoteException;
}
5. stay RemoteService Write code
Realization aidl Code
// Set remote service status , The default is false( Not connected )
private boolean isConnected=false;
// The following three methods are carried out in the child thread of the new process , therefore Toast Use handle For thread communication
private Handler handler=new Handler(Looper.getMainLooper());
private IConnectionService connectionService=new IConnectionService.Stub() {
@Override
public void connect() throws RemoteException {
// Simulate new process time-consuming operations
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 {
// Get connection status
return isConnected;
}
};
Back out :
@Override
public IBinder onBind(Intent intent) {
return connectionService.asBinder();
}
6. To write MainActivity, Realize three buttons : Connect , disconnect , Get connection status , Implement monitoring
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>
The shortcut initializes and listens for the button
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. initialization AIDL Created java The class interface
stay ServiceConnected The rewrite method of onServiceConnected In the initialization

Code :
// initialization aidl Created interface
mConnectionService = IConnectionService.Stub.asInterface(service);
8. Calling method :

Code :
Connect
// Connect
try {
mConnectionService.connect();
} catch (RemoteException e) {
e.printStackTrace();
}
disconnect
// To break off
try {
mConnectionService.disconnect();
} catch (RemoteException e) {
e.printStackTrace();
}
Get connection status :
try {
connection = mConnectionService.isConnection();
} catch (RemoteException e) {
e.printStackTrace();
}
Toast.makeText(this, String.valueOf(connection), Toast.LENGTH_SHORT).show();
3. Reflection and summary
1.
2.
3.
4.
5.
6.
版权声明
本文为[osc_252iaxru]所创,转载请带上原文链接,感谢
边栏推荐
- 接口测试如何在post请求中传递文件
- 服务应用 ClockService安卓实现闹钟
- “开源软件供应链点亮计划 - 暑期 2020”公布结果 基于 ChubaoFS 开发的项目获得最佳质量奖
- 分库分表的 9种分布式主键ID 生成方案,挺全乎的
- 医疗项目管理的三种实用技巧
- Using stream to read and write files to process large files
- New features of Fedora 33 workstation
- How to ensure that messages are not consumed repeatedly? (how to ensure the idempotent of message consumption)
- Windows must be installed with efficiency software!
- Review of hot spots of last week (11.2-11.8)
猜你喜欢

阿里、腾讯、百度、网易、美团Android面试经验分享,拿到了百度、腾讯offer

Mapstructure detoxifies object mapping

SQL第二章第三章

20201107第16课,使用Apache服务部署静态网站;使用Vsftpd服务传输文件

未来中国电信将把云计算服务打造成为中国电信的主业

在企业的降本增效诉求下,Cube如何助力科盾业务容器化“一步到位”?

Tidb x micro banking reduces time consumption by 58%, and distributed architecture helps to realize inclusive finance

Source code analysis of ThinkPHP framework execution process

手写Koa.js源码

The choice of domain name of foreign trade self built website
随机推荐
SQL statement to achieve the number of daffodils
Interface tests how to pass files in post requests
从编码、网络传输、架构设计揭秘腾讯云高质量、高可用实时音视频技术实践...
嘉宾专访|2020 PostgreSQL亚洲大会阿里云数据库专场:樊文凯
Complete set of linked list operations of data structure and algorithm series (3) (go)
An attempt to read or write to protected memory occurred using the CopyMemory API. This usually indicates that other memory is corrupted.
Android NDK 开发实战 - 微信公众号二维码检测
2020.11.07面试总结(面试12k)
Sql分组查询后取每组的前N条记录
After SQL group query, get the first n records of each group
VisualStudio(Mac)安装过程笔记
Shoes? Forecasting stock market trends? Taobao second kill? Python means what you want
In the future, China Telecom will make cloud computing service the main business of China Telecom
The middle stage of vivo Monkey King activity
Looking for better dynamic getter and setter solutions
详解Python input()函数:获取用户输入的字符串
Tidb x micro banking reduces time consumption by 58%, and distributed architecture helps to realize inclusive finance
Oh, my God! Printing log only knows log4j?
接口测试如何在post请求中传递文件
接口测试如何在post请求中传递文件