Let us learn together how to use AIDL, it is not difficult (Android)

Introduction
This article describes what is AIDL most basic use (create, load), on AIDL for deeper understanding, in a subsequent essay, we will continue to share and discuss.

text

  • AIDL definition (what is AIDL?)
  • AIDL application scenarios (AIDL can you do?)
  • How to write a AIDL of application? (Code)

AIDL Overview (definitions)

  • AIDL: Android Interface Definition Language, that is, Android Interface Definition Language. In other words: AIDL also a language.
  • Designed to AIDL language: In order to achieve inter-process communication.
    This article describes a AIDL of code. On the analysis of inter-process communication, little friends can refer to: On Communications (AIDL and IPC) between the application process

AIDL scenarios

  • Such as: an application calls the Alipay payment functions, micro-channel payment functions

Write a AIDL application of AIDL template code

*与你一步步掌握AIDL的应用*

demand

  • Application A: Analogue a shopping mall application (such as: spell XX)
  • Application B: simulate a payment application (such as: payment Po), there is a payment service application is running, the service payment method is defined with a return value.
  • Requirements: The application of A, B payment method of payment services in the calling application, pass a parameters and get the return value.

Code

Application B: callee

    1. Create a service: AliPayService, and configuration information in the manifest file
  • AndroidManifest.xml
        <!--调用远程服务,需要通过bind方式启动服务,调用服务方法-->
        <service android:name=".service.pay.AliPayService">
            <intent-filter>
                <action android:name="com.zero.notes.service.pay.xxx"/>
            </intent-filter>
        </service>
  • AliPayService
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
/**
 * 模拟:阿里支付服务
 */
public class AliPayService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    //模拟支付方法
    public boolean aliPay(int money) {
        Log.e("AIDL", "服务线程:" + Thread.currentThread().getName());
        if (money > 100) {
            handler.sendEmptyMessage(1);
            return true;
        } else {
            handler.sendEmptyMessage(0);
            return false;
        }
    }

//    class MyBinder extends Binder implements IPayservice {
//        @Override
//        public boolean callAliPay(int money) throws RemoteException {
//            return aliPay(money);
//        }
//        @Override
//        public IBinder asBinder() {
//            return null;
//        }
//    }
    /**
     * 创建中间人对象(中间帮助类)
     */
    class MyBinder extends IPayservice.Stub {
        @Override
        public boolean callAliPay(int money) {
            return aliPay(money);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Toast.makeText(getApplicationContext(), "土豪,购买成功...", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "钱太少啦,购买失败...", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
  • IPayservice.aidl
    to note here: IPayservice.aidl file created is an interface file. You can create a AIDL file directly on the Android Studio. Once created, remember: the entire project clean and let the code editor to generate the necessary file information. (Android Studio project clean way: Build -> Clean Project)
// IPayservice.aidl
package com.zero.notes.service.pay;
// Declare any non-default types here with import statements
interface IPayservice {
  boolean callAliPay(int money);
}
  • MainActivity
    application B started the service (Code written: kotlin language)
class MainActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initData()
    }
    private fun initData() {
        val intent = Intent(this,AliPayService::class.java)
        startService(intent)
    }
}

Application A: The caller (write code: Kotlin language)

  • Copy: copy IPayservice.aidl file into the application B of A application
    time remember :: copy, path location IPayservice.aidl must remain fully consistent with the application B, the package name, path name to be exactly the same!
    As shown: FIG 1️⃣ embodiment is Android view; FIG 2️⃣ Project is a view mode.

  • Create a service connection objects
//创建一个服务连接对象
class MyServiceConnection : ServiceConnection {

    private lateinit var iPayService: IPayservice

    override fun onServiceDisconnected(name: ComponentName?) {
    }
    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        //2. 获取中间人对象(服务绑定成功后会返回一个中间人对象)
        iPayService = IPayservice.Stub.asInterface(service)
    }
    //获取中间人对象
    fun getIPayService():IPayservice{
        return iPayService
    }
}
  • Call service method of application A Activity
class MainActivity : AppCompatActivity() {

    private var connection: MyServiceConnection? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intent = Intent()
        intent.action = "com.zero.notes.service.pay.xxx"
        intent.setPackage("com.zero.notes")
        connection = MyServiceConnection()
        bindService(intent, connection, Context.BIND_AUTO_CREATE)

        tvJump.setOnClickListener {
            val iPayService = connection?.getIPayService()
            val pay = iPayService?.callAliPay(1000)!!
            if (pay) {
                //购买成功
            } else {
                //购买失败
            }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        if (connection != null) {
            unbindService(connection)
            connection = null
        }
    }
}
  • Application A: Activity xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:gravity="center_horizontal"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <TextView
            android:id="@+id/tvJump"
            android:layout_width="wrap_content"
            android:layout_marginTop="30dp"
            android:text="AIDL调用方法"
            android:textColor="#FF212121"
            android:textSize="20sp"
            android:padding="16dp"
            android:background="#66000000"
            android:textStyle="bold"
            android:layout_height="wrap_content"/>
</LinearLayout>

Guess you like

Origin www.cnblogs.com/io1024/p/11573484.html