当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- Dynamo: a typical distributed system analysis
- 理解 OC 中 RunLoop
- 使用TreeView树型菜单栏(递归调用数据库自动创建菜单)
- android studio创建平板模拟器方法
- 服务应用 ClockService安卓实现闹钟
- Windows must be installed with efficiency software!
- 手写Koa.js源码
- A simple way to realize terminal text paste board
- The history of C1 research in Shenzhen
- 从编码、网络传输、架构设计揭秘腾讯云高质量、高可用实时音视频技术实践...
猜你喜欢

Stack & queue (go) of data structure and algorithm series

JVM学习(四)-垃圾回收器和内存分配

Android权限大全

Depth analysis based on synchronized lock

Well, the four ways to query the maximum value of sliding window are good

Android rights

Complete set of linked list operations of data structure and algorithm series (3) (go)

After SQL group query, get the first n records of each group

解决IDEA快捷键 Alt+Insert 失效的问题

服务应用 ClockService安卓实现闹钟
随机推荐
iPhone“连到系统上的设备没有发挥作用”原因分析及解决方法 20200105
天啦撸!打印日志竟然只晓得 Log4j?
SQL Chapter 2 Chapter 3
Setting up a proxy for the WGet command
Source code analysis of ThinkPHP framework execution process
“开源软件供应链点亮计划 - 暑期 2020”公布结果 基于 ChubaoFS 开发的项目获得最佳质量奖
Mac terminal oh my Zsh + solarized configuration
Stack & queue (go) of data structure and algorithm series
Sql分组查询后取每组的前N条记录
Review of hot spots of last week (11.2-11.8)
The third way to realize webrtc in embedded devices
As a user, you can't get rid of the portrait!
inet_pton()和inet_ntop()函数详解
Well, these four ways to query the maximum value of sliding window are good
Open source ERP recruitment
使用CopyMemory API出现 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
深圳C1考证历程
接口测试如何在post请求中传递文件
JVM learning (4) - garbage collector and memory allocation
Android权限大全