跨應用啟動service&&AIDL


1、AIDL(android接口定義語言) 是 Android 提供的用於與 Service 進行跨應用、跨進程通信的一種機制,高效、靈活,使用方便。

2、android5.0之前都可以通過配置在manifest里service 的action來啟動。android5.0之后都必須使用顯示intent。

3、跨應用啟動service

  • 一個應用manifest
  • <service
                android:name=".AppService"
                android:enabled="true"
                android:exported="true">
            </service>

     

  • 另一個啟動應用
  • intent = new Intent();
    intent.setComponent(new ComponentName("com.example.startservicefromanother", "com.example.startservicefromanother.AppService"));//第一個參數是包名,第二個是類名
    startService(intent);

     

4、跨應用綁定service並通信

  • 所有的.aidl文件已經需要傳遞的對象接口需要在Service 與Client中各一份。並且必須處於相同的包名之下。添加成功之后,clean一下。adt插件會自動生成.java文件。
  •  aidl文件:
  • package com.example.AIDL;
    
    interface IAppServiceBinder{
        void SetString(String Data);
        void basicTypes(int anInt, long aLong, boolean aBoolean, 
            float aFloat,double aDouble, String aString);
    }

     

  • anotherapp獲得binder:
  • private com.example.AIDL.IAppServiceBinder binder = null;
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1) {
        //這里不能強制轉換,因為雖然類的內容是一樣的,但是卻不是同一個。(每個app能訪問到的畢竟是自己的類)
      binder = com.example.AIDL.IAppServiceBinder.Stub.asInterface(arg1);
    }

     

  • startfromanotherapp中的service代碼:
  • @Override
        public IBinder onBind(Intent intent) {
            return new com.example.AIDL.IAppServiceBinder.Stub() {
                @Override
                public void basicTypes(int anInt, long aLong, boolean aBoolean,
                        float aFloat, double aDouble, String aString)
                        throws RemoteException {
                    // TODO Auto-generated method stub
                    
                }
                
                @Override
                public void SetString(String Data) throws RemoteException {
                    AppService.this.data = Data;
                }
            };
        }

     

  • 其余的操作無差別。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM