android aidl(android studio)

1.aidl service端

1)创建aidl文件

New--->AIDL--->AIDL file

就会生成一个IPerson.aidl文件

 

// IPerson.aidl
package com.example.aidlserverdemo;

// Declare any non-default types here with import statements

interface IPerson {
    void setAge(int age);
    void setName(String name);
    String display();
}

2)aidl文件编写完毕之后,需要Build--->Make Module 'aidlserverdemo',生成相应的java文件。

 IPerson.java文件目录如下:

 

3)aidl接口的实现类(IPersonImpl)

package com.example.aidlserverdemo;

import android.os.RemoteException;

public class IPersonImpl extends IPerson.Stub {

    // 声明两个变量
    private int age;
    private String name;

    @Override
    public void setAge(int age) throws RemoteException {
        this.age = age;
    }

    @Override
    public void setName(String name) throws RemoteException {
        this.name = name;
    }

    @Override
    public String display() throws RemoteException {
        return "name:zzz;age=18";
    }
}

4)MyRemoteService

package com.example.aidlserverdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyRemoteService extends Service {

    // 声明IPerson接口
    private Binder iPerson;


    @Override
    public void onCreate() {
        super.onCreate();
        if (iPerson == null) {
            iPerson = new IPersonImpl();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return iPerson;
    }

}

5)AndroidManifest.xml

        <service
            android:name=".MyRemoteService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.aidlserverdemo.MyRemoteService" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>

 

6)开启服务

注意这里有两个坑,第一个就是Intent的action一定要写AndroidManifest.xml里面service的action;

package com.example.aidlserverdemo;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();
        // 设置Intent的Action 属性
        intent.setAction("com.example.aidlserverdemo.MyRemoteService");

        Intent finalIntent = IntentUtils.createExplicitFromImplicitIntent(this, intent);
        // 绑定服务
        startService(finalIntent);
    }
}

第二个坑就是需要将隐式的intent转变为显示的intent

package com.example.aidlserverdemo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.List;

public class IntentUtils {

    /***
     * Android L (lollipop, API 21) introduced a new problem when trying to invoke implicit intent,
     * "java.lang.IllegalArgumentException: Service Intent must be explicit"
     *
     * If you are using an implicit intent, and know only 1 target would answer this intent,
     * This method will help you turn the implicit intent into the explicit form.
     *
     * Inspired from SO answer: http://stackoverflow.com/a/26318757/1446466
     * @param context
     * @param implicitIntent - The original implicit intent
     * @return Explicit Intent created from the implicit original intent
     */
    public static Intent createExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }

        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);

        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);

        // Set the component to be explicit
        explicitIntent.setComponent(component);

        return explicitIntent;
    }

}

然后将service端运行开启,因为client是基于service的,一定要开启。

2.aidl client端

1.IPerson.aidl

把服务端的IPerson.aidl拷贝过来,并执行Build--->Make Module 'aidlserverdemo'

1)创建ServiceConnection对象

    // 实例化ServiceConnection
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        synchronized public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("MainActivity","onServiceConnected()---------->");
            // 获得IPerson接口
            iPerson = IPerson.Stub.asInterface(service);
            Log.d("MainActivity","iperson----------:" + iPerson);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("MainActivity","onServiceDisconnected()---------->");
            iPerson = null;
        }
    };

2)绑定

注意这里也有坑,必须加上package和action,package是服务端的包名,action是上面service的action。

        Intent intent = new Intent();
        //在5.0及以上版本必须要加上这个
        intent.setPackage("com.example.aidlserverdemo");
        intent.setAction("com.example.aidlserverdemo.MyRemoteService");//这个是上面service的action
        bindService(intent, conn, Service.BIND_AUTO_CREATE);

 3)调用

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String msg = iPerson.display();
                    // 显示方法调用返回值
                    Log.d("MainActivity", "msg====>" + msg);
                } catch (Exception e) {
                    Log.d("MainActivity", "e====>" + e);
                    e.printStackTrace();
                }
            }
        });

4)解绑

    @Override
    protected void onDestroy() {
        if (conn != null) {
            unbindService(conn);
        }
        super.onDestroy();
    }

5)运行结果:

2020-07-02 09:56:20.461 9151-9151/com.example.aidlclientdemo D/MainActivity: msg====>name:zzz;age=18

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android Studio中的AIDLAndroid接口定义语言的缩写,它是一种用于定义Android应用程序中的进程间通信(IPC)接口的语言。使用AIDL,您可以定义客户端和服务之间的接口,以便它们可以相互通信和交换数据。在Android应用程序中,AIDL通常用于实现跨进程通信,例如在应用程序中使用服务来执行后台任务。 ### 回答2: Android Studio AIDLAndroid Interface Definition Language)是一种用于在Android应用程序中进行进程间通信(IPC)的技术。它允许不同应用程序或同一应用程序中的不同进程之间进行数据和指令的传输和共享。AIDL基于Binder机制实现,是许多Android系统服务和框架中广泛使用的IPC技术。 在Android Studio中使用AIDL,首先需要创建一个AIDL接口,该接口定义了可用于在不同进程之间进行通信的方法。一旦创建了该接口,它可以在应用程序中使用,与其他进程交换数据和指令。AIDLAndroid系统自动创建和管理,不需要手动实现Binder机制。 使用AIDL的主要优点是实现非常方便,而且可以跨多个进程使用。它使得应用程序能够高效地共享数据和指令,并允许不同进程之间进行通信,从而扩展了Android应用程序的功能和交互性。 一些开发人员可能认为AIDL的学习和使用有一定的难度,但是一旦了解了AIDL的基本原理和使用方法,就能够轻松实现IPC功能,并创建更高效的Android应用程序。总之,通过使用AIDLAndroid应用程序开发人员可以实现更好的应用程序设计和创新,并提高应用程序的性能和用户体验。 ### 回答3: Android Studio AIDLAndroid Interface Definition Language)是一种跨进程通信的机制,用于在不同的Android组件之间进行通信。 AIDL类似于SOAP(Simple Object Access Protocol),RPC(Remote Procedure Call)或CORBA(Common Object Request Broker Architecture),它是一种高级的RPC机制,允许不同的应用程序使用相同的接口来进行通信。 AIDL的主要作用是允许一个应用程序通过一个中间层向另外的一个应用程序发送请求,并且读取响应信息。它是Android操作系统提供的默认RPC机制,由于基于Binder实现,因此具备更高的性能和更好的稳定性。 AIDL可以让你定义一组接口,用来描述应用组件之间的通信方法,包括输入和输出参数。AIDL文件定义完毕后,你可以使用Android Studio自动生成AIDL接口的Java类,以便你可以跨进程访问该接口。 使用AIDL的好处是,可以将系统拆分成独立的组件,这些组件可以在不同的进程之间进行通信,从而实现了更好的资源利用和更加灵活的架构设计。 总之,Android Studio AIDL是一种强大的跨进程通信机制,有助于提高应用程序的性能和稳定性,从而让我们能够更好地设计和开发更高效的Android应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值