aidl 中通过RemoteCallbackList 运用到的回调机制: service回调activity的方法
说明:我没有写实例代码,直接拿项目中的代码,有点懒了,这里我省略贴出两个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();
- }
- }