android aidl(android studio)
16lz
2021-01-23
1.aidl service端
1)创建aidl文件
New--->AIDL--->AIDL file
就会生成一个IPerson.aidl文件
// IPerson.aidlpackage com.example.aidlserverdemo;// Declare any non-default types here with import statementsinterface 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
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 = 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
更多相关文章
- 【Android】图片切换组件ImageSwitcher的运用
- Android 创建圆形背景图片
- android用于打开各种文件的intent
- Android base64 上传图片
- Android显示网络图片相关实现方法浅谈
- android 中Drawable跟Bitmap转换及常用于图片相关操作方法 - And
- Delphi XE5 for android 调用Java类库必看的文件
- android带图片的AlertDialog和文件管理器(代码)