zoukankan      html  css  js  c++  java
  • 写一个简单的AIDL

    1.首先创建一个AIDL文件,并添加上两个接口。
    IMyAidlInterface.aidl

    package com.example.broadcastdemo;

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

    interface IMyAidlInterface {

    void request();
    String getName();
    }


    2.编写服务端实现AIDL相应的接口
    MyService.java

    public class MyService extends Service {
    public MyService() {
    }

    private final IBinder iBinder = new IMyAidlInterface.Stub() {
    @Override
    public void request() throws RemoteException {


    }

    @Override
    public String getName() throws RemoteException {
    return "您好,我的名字叫服务端";
    }
    };

    @Override
    public void onCreate() {
    super.onCreate();
    }

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

    }


    3:使用

    private void binAidl() {
    if (myAidlInterface == null) {
    try {
    Intent intent = new Intent("com.example.broadcastdemo.MyService");
    intent.setPackage("com.example.broadcastdemo");
    boolean result = bindService(intent, ServiceConnection, Context.BIND_AUTO_CREATE);
    Log.e(TAG, "createPopupServiceConnection: result " + result);
    }catch (Exception e){
    Log.e(TAG, "createPopupServiceConnection: Exception" + e.getLocalizedMessage());
    }

    }
    }

    private android.content.ServiceConnection ServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    Log.e(TAG, "onServiceConnected: ServiceConnection");
    myAidlInterface = IMyAidlInterface.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    Log.e(TAG, "onServiceDisconnected: ServiceConnection");
    myAidlInterface = null;
    }
    };


    private void getName(){
    if (myAidlInterface != null) {
    try {
    String str = myAidlInterface.getName();
    Log.e(TAG, "" + str);
    } catch (RemoteException e) {
    e.printStackTrace();
    }
    }
    }
  • 相关阅读:
    敏捷开发中的故事点到底是什么?如何预估故事点?
    Worktile 进军软件开发与协作的初心与野心
    宽带无法登陆GitHub解决——修改host
    IDEA自定义类注释和方法注释(自定义groovyScript方法实现多行参数注释)
    SpringBoot2.x整合redis和使用redis缓存
    简单聊聊JVM
    IDEA打包web项目为war,通过本地Tomcat启动war
    多表更新
    unittest suite集合实现原理
    14.0 native webview H5切换
  • 原文地址:https://www.cnblogs.com/mwl523/p/14084353.html
Copyright © 2011-2022 走看看