当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- JVM学习(六)-内存模型和线程
- 医疗项目管理的三种实用技巧
- 20201107第16课,使用Apache服务部署静态网站;使用Vsftpd服务传输文件
- “开源软件供应链点亮计划 - 暑期 2020”公布结果 基于 ChubaoFS 开发的项目获得最佳质量奖
- Visual Studio (MAC) installation process notes
- 技美那么贵,不如找顾问 | AALab企业顾问业务
- 嘉宾专访|2020 PostgreSQL亚洲大会阿里云数据库专场:樊文凯
- The history of C1 research in Shenzhen
- Pay attention to the request forwarding problem of. Net core
- 分库分表的 9种分布式主键ID 生成方案,挺全乎的
猜你喜欢
Understanding runloop in OC
利用 Python 一键下载网易云音乐 10W+ 乐库
一个简单的能力,决定你是否会学习!
Mac terminal oh my Zsh + solarized configuration
Configure switch trunk interface traffic local priority forwarding (cluster / stack)
Stack & queue (go) of data structure and algorithm series
Ali, Tencent, Baidu, Netease, meituan Android interview experience sharing, got Baidu, Tencent offer
Is SEO right or wrong?
Understanding task and async await
Biden wins the US election! Python developers in Silicon Valley make fun of Ku Wang in this way
随机推荐
Analysis of the source code of ThinkPHP facade
Show profile analysis of SQL statement performance overhead
安卓开发——服务应用,计时器的实现(线程+服务)
利用 Python 一键下载网易云音乐 10W+ 乐库
Android架构之Navigation组件(二)
Safety (miscellany)
共创爆款休闲游戏 “2020 Ohayoo游戏开发者沙龙”北京站报名开启
Is SEO right or wrong?
Wechat circle
Solve the problem of idea shortcut key Alt + insert invalid
解决IDEA快捷键 Alt+Insert 失效的问题
Reread reconstruction
Dynamo: a typical distributed system analysis
An attempt to read or write to protected memory occurred using the CopyMemory API. This usually indicates that other memory is corrupted.
Source code analysis of ThinkPHP framework execution process
走进京东 | 中国空间技术研究院青年创新联盟成员莅临参观京东总部
TiDB x 微众银行 | 耗时降低 58%,分布式架构助力实现普惠金融
Python零基础入门教程(01)
Front end code style practice prettier + eslint + git hook + lint staged
Download Netease cloud music 10W + music library with Python