aidl 中通过RemoteCallbackList 运用到的回调机制: service回调activity的方法
方法 通过 机制 Service Activity 运用 回调 AIDL
2023-09-14 09:11:28 时间
说明:我没有写实例代码,直接拿项目中的代码,有点懒了,这里我省略贴出两个aidl文件。
TtsService extends Service
- private final RemoteCallbackList<ITtsCallback> mCallbacks
- = new RemoteCallbackList<ITtsCallback>();
- private final android.speech.tts.ITts.Stub mBinder = new Stub() {
- public int registerCallback(String packageName, ITtsCallback cb) {
- if (cb != null) {
- mCallbacks.register(cb);
- mCallbacksMap.put(packageName, cb);
- return TextToSpeech.SUCCESS;
- }
- return TextToSpeech.ERROR;
- }
- public int unregisterCallback(String packageName, ITtsCallback cb) {
- if (cb != null) {
- mCallbacksMap.remove(packageName);
- mCallbacks.unregister(cb);
- return TextToSpeech.SUCCESS;
- }
- return TextToSpeech.ERROR;
- }
- public int speak(String callingApp, String text, int queueMode, String[] params) {
- ArrayList<String> speakingParams = new ArrayList<String>();
- if (params != null) {
- speakingParams = new ArrayList<String>(Arrays.asList(params));
- }
- return this.speak(callingApp, text, queueMode, speakingParams);
- }
- private void dispatchProcessingCompletedCallback(String packageName) {
- ITtsCallback cb = mCallbacksMap.get(packageName);
- if (cb == null){
- return;
- }
- //Log.i("TtsService", "TTS callback: dispatch started");
- // Broadcast to all clients the new value.
- final int N = mCallbacks.beginBroadcast();
- try {
- cb.processingCompleted();
- } catch (RemoteException e) {
- // The RemoteCallbackList will take care of removing
- // the dead object for us.
- }
- mCallbacks.finishBroadcast();
- //Log.i("TtsService", "TTS callback: dispatch completed to " + N);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- // TODO replace the call to stopAll() with a method to clear absolutely all upcoming
- // uses of the native synth, including synthesis to a file, and delete files for which
- // synthesis was not complete.
- stopAll();
- // Unregister all callbacks.
- mCallbacks.kill();
- }
在activity中
- mITtscallback = new ITtsCallback.Stub() {
- public void processingCompleted() throws RemoteException {
- if (listener != null) {
- listener.onProcessingCompleted();
- }
- }
- };
- result = mITts.registerCallback(mPackageName, mITtscallback);
上面只是一个贴代码没有做任何说明,基本的意思我想大家也能通过代码来看懂。
- // int N = mCallbacks.beginBroadcast();
- // try {
- // for (int i = 0; i < N; i++) {
- // mCallbacks.getBroadcastItem(i).showResult(mSlot);
- // }
- // } catch (RemoteException e) {
- // Log("" + e);
- // }
- // mCallbacks.finishBroadcast();
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
上传一个写的工作中用到的demo
- package com.pateo.aidl;
- interface ICallback {
- void showResult(String result);
- }
- package com.pateo.aidl;
- import com.pateo.aidl.ICallback;
- interface IMyService {
- void init(String packageName,String slot);
- void registerCallback(String packageName,ICallback cb);
- void unregisterCallback(String packageName,ICallback cb);
- }
- package com.pateo.service;
- import java.util.HashMap;
- import android.app.Service;
- import android.content.Intent;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.os.RemoteCallbackList;
- import android.os.RemoteException;
- import com.pateo.aidl.ICallback;
- import com.pateo.aidl.IMyService;
- public class VuiService extends Service {
- private RemoteCallbackList<ICallback> mCallbacks = new RemoteCallbackList<ICallback>();
- private HashMap<String, ICallback> mCallbacksMap = new HashMap<String, ICallback>();
- private String mSlot = "";
- private String mPackageName = "";
- @Override
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
- }
- @Override
- public IBinder onBind(Intent intent) {
- return remoteBinder;
- }
- @Override
- public void onDestroy() {
- mHandler.removeMessages(0);
- mCallbacks.kill();
- super.onDestroy();
- }
- @Override
- public boolean onUnbind(Intent intent) {
- return super.onUnbind(intent);
- }
- public void onRebind(Intent intent) {
- super.onRebind(intent);
- }
- private IMyService.Stub remoteBinder = new IMyService.Stub() {
- @Override
- public void init(String packageName,String slot) throws RemoteException {
- mSlot = slot;
- mPackageName = packageName;
- //Ä£Ä⿪ʌÆô¶¯Ê¶±ð£¬ÕâÀïµÄ4000ºÁÃëÏ൱ÓÚžøÓèµÄʶ±ð¹ý³ÌµÄʱŒä£¬Õâžö¿ÉÒÔÔÚʶ±ðœá¹ûÀïÃæÈ¥µ÷ÓÃ
- mHandler.sendEmptyMessageDelayed(0, 4000);
- }
- @Override
- public void unregisterCallback(String packageName, ICallback cb) {
- if (cb != null) {
- mCallbacks.unregister(cb);
- mCallbacksMap.remove(packageName);
- }
- }
- //°üÃû×¢²áµÄ·œÊœ£¬ÕâÑùŸÍ±ÜÃâÁ˺ܶàÓŠÓÃ×¢²á¶ŒÈ¥»Øµ÷£¬ÕâÀïÍš¹ýÓŠÓÞøÓèµÄpackageNameÀŽÆ¥ÅäŸßÌå»Øµ÷ÄÄÒ»žöÓŠÓõÄcallback
- @Override
- public void registerCallback(String packageName, ICallback cb) {
- if (cb != null) {
- mCallbacks.register(cb);
- mCallbacksMap.put(packageName, cb);
- }
- }
- };
- //ÕâÀïÍš¹ýÓŠÓÞøÓèµÄpackageNameÀŽÆ¥ÅäŸßÌå»Øµ÷ÄÄÒ»žöÓŠÓõÄcallback
- private void dispatchProcessingCompletedCallback() {
- ICallback cb = mCallbacksMap.get(mPackageName);
- if (cb == null){
- return;
- }
- final int N = mCallbacks.beginBroadcast();
- try {
- cb.showResult(mSlot);
- } catch (RemoteException e) {
- }
- mCallbacks.finishBroadcast();
- }
- private Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- dispatchProcessingCompletedCallback();
- super.handleMessage(msg);
- }
- };
- }
- package com.pateo;
- import com.pateo.service.VuiService;
- import com.pateo.aidl.ICallback;
- import com.pateo.aidl.IMyService;
- import com.pateo.R;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.ServiceConnection;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.IBinder;
- import android.os.Message;
- import android.os.RemoteException;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
- public class AppActivity extends Activity {
- TextView tv;
- IMyService myservice ;
- String mResult ;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- tv = (TextView) findViewById(R.id.tv);
- //Ä£Äâ°ŽmodeŒü
- Button btn = (Button) findViewById(R.id.startBtn);
- btn.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(AppActivity.this,VuiService.class);
- bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
- }
- });
- }
- private ServiceConnection serviceConnection = new ServiceConnection() {
- @Override
- public void onServiceDisconnected(ComponentName name) {
- myservice = null;
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- myservice = IMyService.Stub.asInterface(service);
- try {
- if(myservice != null){
- myservice.registerCallback("com.pateo",mCallback);
- myservice.init("com.pateo","ÖØÌý|»ØžŽ");//ΪÁËÓïÒô¿òŒÜœÓÊÕµœÕâЩŽÊºó°ÑÕâÁœžöŽÊ²åÈë²å²Û£¬ÕâÑùŸÍ¿ÉÒÔ·¶Î§Ð¡Ìážßʶ±ð
- //ÕâÀﻹ¿ÉÒÔ×ö°ÑÒ»Œ¶ŽÊÌõÒ²·¢¹ýÈ¥£¬²åÈë²å²Û¡£
- }
- } catch (RemoteException e) {
- }
- }
- };
- /**
- * serviceµÄ»Øµ÷·œ·š
- */
- private ICallback.Stub mCallback = new ICallback.Stub() {
- //µÈŽýʶ±ðœá¹ûÈ»ºóshow³öÀŽ
- @Override
- public void showResult(String result) {
- try {
- mResult = result;
- Message msgget = Message.obtain();
- msgget.what = 1;
- mHandler.sendMessage(msgget);
- } catch (Exception e) {
- }
- }
- };
- private Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- switch (msg.what) {
- case 1:
- tv.setText("result : " + mResult);
- break;
- }
- }
- };
- @Override
- protected void onDestroy() {
- unbindService(serviceConnection);
- super.onDestroy();
- }
- }
相关文章
- [Android Pro] Android系统手机端抓包方法 和 通过File查看应用程序流量
- 通过JavaScript实现在线测试HTTP延迟方法
- 通过反射获取方法返回的类型
- 通过反射获取方法返回的类型
- 详细讲解提高数据库查询效率的实用方法、外键关于性能
- JEECG中的validform验证ajaxurl的使用方法
- 《转》Visual Studio 2010 终极定制安装精简方法
- shell脚本执行时报"bad interpreter: Text file busy"的解决方法
- Python实现按照指定要求逆序输出一个数字的方法
- linux下通过iptables只允许指定ip地址访问指定端口的设置方法
- java反射机制,通过类名获取对象,通过方法名和参数调
- Teradata 终止回滚方法(rcvmanager工具)
- linux Xtrabackup安装及使用方法
- 简介Python设计模式中的代理模式与模板方法模式编程
- linux 从百度网盘下载文件的方法
- Atitit.通过null 参数 反射 动态反推方法调用
- Atitit.通过null 参数 反射 动态反推方法调用
- SAP UI5 应用开发教程之五十七 - 基于 OData 注解的 Smart Field 使用方法学习试读版
- ML:分类预测任务中模型评估指标(ER/混淆矩阵ACC、Precision、Recall、AP、mAP、F1、ROC-AUC)简介、使用方法、代码实现、案例应用之详细攻略
- 关于 xlrd.biffh.XLRDError: Excel xlsx file; not supported 解决方法【已解决】
- python类与类方法的实现
- RecyclerView实现一个页面有多种item,每个item有多个view,并且可以让任意item的任意view自定义监听,通过接口方法进行触发操作
- 【Groovy】MOP 元对象协议与元编程 ( 使用 Groovy 元编程进行函数拦截 | 通过 MetaClass#invokeMethod 方法调用类其它方法 )
- Java中Scanner的使用方法
- Ubuntu20.04无法调节亮度问题(尝试各种方法后最终通过升级内核解决)
- PySpark 的背后原理--在Driver端,通过Py4j实现在Python中调用Java的方法.pyspark.executor 端一个Executor上同时运行多少个Task,就会有多少个对应的pyspark.worker进程。
- Py之requests:python的requests包的简介、安装、使用方法详细攻略