How to call a method in activity from a service

前端 未结 4 762
失恋的感觉
失恋的感觉 2020-12-08 07:14

There is a service that listens for some voice. If voice matches a string a certain method is invoked in the service object.

public class SpeechActivationSe         


        
4条回答
  •  没有蜡笔的小新
    2020-12-08 07:35

    After some research I found the following timings in my case for sending and receiving the broadcast. I have service in the same process.

    sendBroadcast (Not recommended if both components are in same process) 34 sec

    LocalBroadcastManager.getInstance(this).sendBroadcast(intent); close to 30 sec

    Implementing using AIDL and RemoteCallbackList Will work for same process or different process

    In your service

    public final RemoteCallbackList mDMCallbacks = new RemoteCallbackList();
    
    public void registerDMCallback(ICallBackAidl cb) {
        Logger.d(LOG_TAG, "registerDMCallback " + cb);
        if (cb != null)
            mDMCallbacks.register(cb);
    }
    

    When you need call methods in Application/Acitvity from service

    public void callMehodsInApplication() {
        final int N = mDMCallbacks.beginBroadcast();
        for (int i = 0; i < N; i++) {
            try {
                mDMCallbacks.getBroadcastItem(i).method1();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        mDMCallbacks.finishBroadcast();
    }
    

    In your class extending Application or Activity.

    private ISyncmlServiceDMCallback mCallback = new ISyncmlServiceDMCallback.Stub() {
     // Implement callback methods here
      public void method1() {
           // Service can call this method
      }
    }
    
     public void onServiceConnected(ComponentName name, IBinder service) {   
            svc.LocalBinder binder = (svc.LocalBinder) service;
            mSvc = binder.getService();
            mSvc.registerDMCallback(mCallback);
     }
    

    Calling this way is almost instantaneous from broadcasting and receiving from the same process

提交回复
热议问题