Android Studio的笔记--aidl实现和调用

aidl实现

新建aidl实现工程

新建一个工程。工程名testaidl。包名com.lxh.testaidl。修改配置文件

build.gradle

a
修改sdk配置,修改version,修改生成apk命名,修改编译混淆配置,增加系统签名
文件位置:\testaidl\app
文件名:build.gradle
在这里插入图片描述

plugins {
    id 'com.android.application'
}
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"
    defaultConfig {
        applicationId "com.lxh.testaidl"
        minSdkVersion 28
        targetSdkVersion 30
        versionCode 1
        def date = new Date().format("yyyyMMddHHmm" , TimeZone.getTimeZone("GMT+08"))
        versionName "testaidl-V1.0-"+date
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    android.applicationVariants.all {
        variant ->
            variant.outputs.all {
                outputFileName = new File(defaultConfig.versionName + ".apk");
            }
    }
    signingConfigs {
        release {
            storeFile file("../keystore/mykey.jks")
            storePassword '123456'
            keyAlias '_mykey'
            keyPassword '123456'
        }
        debug {
            storeFile file("../keystore/mykey.jks")
            storePassword '123456'
            keyAlias '_mykey'
            keyPassword '123456'
        }
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

b
修改build variants中active build variant 从debug改成release
在这里插入图片描述
c
签名文件
文件位置:\testaidl\keystore
文件名:mykey.jks

proguard-rules.pro

增加混淆
文件位置:\testaidl\app
文件名:proguard-rules.pro

-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-verbose
-dontoptimize
-dontpreverify
-keepattributes *Annotation*
-keep public class com.google.vending.licensing.ILicensingService
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclassmembers public class * extends android.view.View {
void set*(***);
*** get*();
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator CREATOR;
}
-keepclassmembers class **.R$* {
public static <fields>;
}
-dontwarn android.support.**
-keep class android.support.annotation.Keep
-keep @android.support.annotation.Keep class * {*;}
-keepclasseswithmembers class * {
@android.support.annotation.Keep <methods>;
}
-keepclasseswithmembers class * {
@android.support.annotation.Keep <fields>;
}
-keepclasseswithmembers class * {
@android.support.annotation.Keep <init>(...);
}
-optimizationpasses 5
-dontusemixedcaseclassnames
-ignorewarnings
-keep class com.lxh.testaidl.USTservice { *; }
-keep public class com.lxh.testaidl.aidl.UST {*;}

增加aidl文件

增加aidl文件
文件位置:testaidl\app\src\main\aidl\com\lxh\testaidl\aidl
文件名:UST.aidl

package com.lxh.testaidl.aidl;

interface UST {

    int installPackage(String filepath,int indicator,String version);
   
}

增加aidl实现

编译一遍,能import aidl出来
import com.lxh.testaidl.aidl.UST;

aidl实现服务

新增service,命名USTservice

package com.lxh.testaidl;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;

import com.lxh.testaidl.aidl.UST;

/**
 * create by lxh on 2022/12/12 Time:14:35
 * tip:
 */
public class USTservice extends IntentService {
    private static final String TAG = "USTservice lxh";

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent");
        if (intent != null) {
            final String action = intent.getAction();
        }
    }

    public TatvUSTservice() {
        super("USTservice");
        Log.i(TAG, "USTservice");
    }

    public UST.Stub asBinder = new UST.Stub() {
        @Override
        public int installPackage(String filepath, int indicator, String version) throws RemoteException {
            Log.i(TAG, "installPackage(" + filepath + "," + indicator + "," + version);
            String callerId = getApplicationContext().getPackageManager().getNameForUid(asBinder.getCallingUid());
            Log.i(TAG, "Calling App:" + callerId);
            if (callerId.equals("com.lxh.useraidl")) {
                //在这里放实际的代码
            }
            return 1;
        }
    };


    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return asBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind");
        return true;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
    }

    public int installPackage(String filepath, int indicator, String version) {
        int value = 0;
        switch (indicator) {
            case 1:
                Log.d(TAG, "");
                value = 1;
                break;
            case 2:
                value = 0;
                break;
            default:
                break;
        }
        return value;
    }
}

清单中

<queries>
        <package android:name="com.tatv.android.TMC.aidl" />
    </queries>
    
<service
            android:name=".USTservice"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.lxh.testaidl.aidl.UST" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>

打开aidl服务

b新增开机广播接收BootReceiver,用来打开服务

package com.lxh.testaidl;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

/**
 * create by lxh on 2022/12/12 Time:14:33
 * tip:
 */
public class BootReceiver extends BroadcastReceiver {
    private static final String TAG = "BootReceiver lxh";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "onReceive: " + intent.getAction());
        if (!TextUtils.isEmpty(intent.getAction()) && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Log.i(TAG, "onReceive: ready sent ");
            Intent it1 = new Intent("com.lxh.testaidl.aidl.UST");
            it1.setPackage("com.lxh.testaidl");
            context.startService(it1);
        }
    }
}

清单

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver android:name=".BootReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:priority="1000">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

aidl使用

新建aidl使用工程

新建一个工程。工程名useraidl。包名com.lxh.useraidl。

增加aidl文件

增加aidl文件
文件位置:useraidl\app\src\main\aidl\com\lxh\testaidl\aidl
文件名:UST.aidl

package com.lxh.testaidl.aidl;

interface UST {

    int installPackage(String filepath,int indicator,String version);
   
}

使用aidl方法

package com.lxh.useraidl;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.lxh.testaidl.aidl.UST;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity lxh";
    UST tUST;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=findViewById(R.id.button);

        Intent service = new Intent("com.lxh.testaidl.aidl.UST");
        service.setPackage("com.lxh.testaidl");
        bindService(service, connection, Context.BIND_AUTO_CREATE);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    tUST.installPackage("1",1,"0");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    private ServiceConnection connection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            Log.i(TAG, "tUST");
            tUST = UST.Stub.asInterface(service);
        }
        public void onServiceDisconnected(ComponentName name)
        {
            tUST = null;
        }
    };

}

相关回显

开机广播:am broadcast -a android.intent.action.BOOT_COMPLETED

2023-09-13 10:22:00.081 15635-15635/com.lxh.testaidl I/BootReceiver lxh: onReceive: android.intent.action.BOOT_COMPLETED
2023-09-13 10:22:00.081 15635-15635/com.lxh.testaidl I/BootReceiver lxh: onReceive: ready sent 
2023-09-13 10:22:00.087 15635-15635/com.lxh.testaidl I/USTservice lxh: USTservice
2023-09-13 10:22:00.092 15635-15635/com.lxh.testaidl I/USTservice lxh: onCreate
2023-09-13 10:22:00.093 15635-15635/com.lxh.testaidl I/USTservice lxh: onStartCommand
2023-09-13 10:22:00.113 15635-15790/com.lxh.testaidl I/USTservice lxh: onHandleIntent
2023-09-13 10:22:00.123 15635-15635/com.lxh.testaidl I/USTservice lxh: onDestroy

运行使用aidl工程

2023-09-13 10:24:07.733 16174-16174/com.lxh.useraidl I/MainActivity lxh: tUST

点击按钮使用aidl方法

2023-09-13 10:24:07.637 15635-15635/com.lxh.testaidl I/USTservice lxh: USTservice
2023-09-13 10:24:07.642 15635-15635/com.lxh.testaidl I/USTservice lxh: onCreate
2023-09-13 10:24:07.643 15635-15635/com.lxh.testaidl I/USTservice lxh: onBind
2023-09-13 10:25:23.618 15635-15667/com.lxh.testaidl I/USTservice lxh: installPackage(1,1,0
2023-09-13 10:25:23.619 15635-15667/com.lxh.testaidl I/USTservice lxh: Calling App:com.lxh.useraidl
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio 调用第三方提供的 AIDL,需要进行以下步骤: 1. 在 Android Studio 项目中新建一个 aidl 目录,并在其中创建一个与第三方 AIDL 文件相同的包名和文件名,例如:com.example.remote.aidl.RemoteService.aidl。 2. 将第三方提供的 AIDL 文件复制到新建的 aidl 目录中。 3. 在 app 模块的 build.gradle 文件中添加以下依赖: ``` dependencies { implementation 'com.android.support:support-annotations:28.0.0' } ``` 4. 在 app 模块的 build.gradle 文件中添加以下配置: ``` android { defaultConfig { ... multiDexEnabled true } ... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { ... implementation 'com.android.support:multidex:1.0.3' } ``` 5. 编译项目,生成对应的 Java 文件。 6. 在需要调用第三方 AIDL 的地方,通过以下方式获取远程服务: ``` private IRemoteService mService; private void bindRemoteService() { Intent intent = new Intent(); intent.setPackage("com.example.remote"); intent.setAction("com.example.remote.action.REMOTE_SERVICE"); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IRemoteService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { mService = null; } }; ``` 其中,com.example.remote 是第三方 AIDL 文件的包名,com.example.remote.action.REMOTE_SERVICE 是第三方 AIDL 文件的 action 名称。IRemoteService 是第三方 AIDL 文件中定义的接口名称。在 onServiceConnected 方法中,通过 Stub.asInterface 方法获取远程服务的实例。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值