温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Android中实现跨进程回掉接口

发布时间:2021-03-09 16:20:55 来源:亿速云 阅读:150 作者:Leah 栏目:移动开发

这篇文章将为大家详细讲解有关怎么在Android中实现跨进程回掉接口,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

Android是什么

Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。

首先定义两个AIDL文件:

1.ITestCallBack.aidl

interface ITestCallBack {
 /**
  * Demonstrates some basic types that you can use as parameters
  * and return values in AIDL.
  */
 void onTagValid(in String tag);

}

2.ITestInterface.aidl    在注册和反祖册方法中,需要传入ITestCallBack的对象

interface ITestInterface {
 /**
  * Demonstrates some basic types that you can use as parameters
  * and return values in AIDL.
  */
  boolean isTagValid(in String tag);

  void registerCallback(in String tag, in ITestCallBack callback);

  void unRegisterCallback(in String tag, in ITestCallBack callback);
}

服务端:

         创建Service,并且在service中定义RemoteCallbackList集合,实现ITestInterface.Stub,在registerCallback,和unRegisterCallback中,分别将ITestCallBack对象注册和反注册进RemoteCallbackList中。RemoteCallbackList提供了获取注册进去的IInterface对象方法

//其实RemoteCallbackList类似于java中{@link java.util.Observable},用来批量处理接口回调对象,
//其实如果确保只有一个客户端会bind到这个服务,只需要保存一个IMyAidlInterfaceCallback即可。
//但是如果有多个,强烈推荐使用其实RemoteCallbackList

public void callBack() {
 if (mCallBacks == null) {
  return;
 }
 int num = mCallBacks.beginBroadcast();
 for (int i = 0; i < num; i++) {
  try {
   mCallBacks.getBroadcastItem(i).onTagValid("congratulation callback success " + tag);
  } catch (RemoteException e) {
   e.printStackTrace();
  }
 }
 //结束后一定要使用finsh,否则下次执行beginBroadcast会抛出IllegalStateException异常
 mCallBacks.finishBroadcast();
}

在isTagValid中可以调用callBack方法去遍历注册的接口对象,也可以当服务端有变化时主动调用callBack方法去通知客户端,这样就实现了服务端变化主动通知客户端。可根据实际方法修改。

在service的onBind方法中,返回ITestInterface.Stub的对象即可,等待客户端绑定服务端。

下面是服务端Service的代码:

public class TestService extends Service {

 private RemoteCallbackList<ITestCallBack> mCallBacks = new RemoteCallbackList<>();
 private String tag = "hy";

 public TestService() {
 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO: Return the communication channel to the service.
  return iTestInterface;
 }

 @Override
 public boolean onUnbind(Intent intent) {
  return super.onUnbind(intent);
 }

 ITestInterface.Stub iTestInterface = new ITestInterface.Stub() {
  @Override
  public boolean isTagValid(String tag) throws RemoteException {
   if (tag.equals(TestService.this.tag)) {
    callBack();
    return true;
   }
   return false;
  }

  @Override
  public void registerCallback(String tag, ITestCallBack callback) throws RemoteException {
   if (null != mCallBacks && null != callback) {
    mCallBacks.register(callback);
   }
  }

  @Override
  public void unRegisterCallback(String tag, ITestCallBack callback) throws RemoteException {
   if (null != mCallBacks && null != callback) {
    mCallBacks.unregister(callback);
   }
  }
 };

 public void callBack() {
  if (mCallBacks == null) {
   return;
  }
  int num = mCallBacks.beginBroadcast();
  for (int i = 0; i < num; i++) {
   try {
    mCallBacks.getBroadcastItem(i).onTagValid("congratulation callback success " + tag);
   } catch (RemoteException e) {
    e.printStackTrace();
   }
  }
  mCallBacks.finishBroadcast();
 }
}

客户端:

        客户端首先要做的是绑定服务端,实现AIDL的通信,在客户端创建绑定按钮,解绑按钮,和主动获取信息的通信按钮。在主动获取信息的通信按钮中实现iTestInterface对象的isTagValid方法可以主动去获取服务端的信息(服务端在isTagValid方法中调用了callBack方法)。

客户端代码:

public class MainActivity extends AppCompatActivity {

 private String tag = "hy";
 private ITestInterface iTestInterface;
 private ServiceConnection connection = new ServiceConnection() {
  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   iTestInterface = ITestInterface.Stub.asInterface(service);
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {
   iTestInterface = null;
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  bindService();
  ((Button) findViewById(R.id.buttonregister)).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    try {
     iTestInterface.registerCallback(tag, new ITestCallBack.Stub() {
      @Override
      public void onTagValid(String tag) throws RemoteException {
       Log.e("test", "registerCallback: " + tag);
      }
     });
    } catch (RemoteException e) {
     e.printStackTrace();
    }
   }
  });

  ((Button) findViewById(R.id.buttonunregister)).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    try {
     iTestInterface.unRegisterCallback(tag, new ITestCallBack.Stub() {
      @Override
      public void onTagValid(String tag) throws RemoteException {

      }
     });
    } catch (RemoteException e) {
     e.printStackTrace();
    }
   }
  });

  ((Button) findViewById(R.id.buttonisvalid)).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    try {
     iTestInterface.isTagValid(tag);
    } catch (RemoteException e) {
     e.printStackTrace();
    }
   }
  });
 }

 private void bindService() {
  Intent intent = new Intent();
  intent.setAction("com.example.heyang.myapplication.TestService");
  intent.setPackage("com.example.heyang.myapplication");
  boolean success = bindService(intent, connection, Context.BIND_AUTO_CREATE);
  if (success) {
   Log.e("test ", "bindService OK");
  } else {
   Log.e("test ", "bindService Fail");
  }
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  unBindeService();
 }

 private void unBindeService() {
  try {
   unbindService(connection);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

关于怎么在Android中实现跨进程回掉接口就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI