美文网首页
aidl例子

aidl例子

作者: Android刘东 | 来源:发表于2020-07-17 18:37 被阅读0次

    1.服务工程

    1)new->aidl->
    2)创建IMyAidlInterface 如:

    interface IMyAidlInterface {
        /**
         * Demonstrates some basic types that you can use as parameters
         * and return values in AIDL.
         */
    //    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
    //            double aDouble, String aString);
        String getName();
    }
    
    

    3)make project 编译一下 创建Service

    public class MyService extends Service {
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return new MyBinder();
        }
        class MyBinder extends IMyAidlInterface.Stub{
    
            @Override
            public String getName() {
                return "test";
            }
        }
    }
    
    

    4)AndroidManifest.xml 添加service的action

            <service android:name=".aidl.MyService"
                android:enabled="true"
                android:exported="true">
    
                <intent-filter>
                    <action android:name="com.github.xch168.plugindemo.aidl.MyService" />
                </intent-filter>
            </service>
    
    

    2.客户端工程

    1)把aidl文件复制下来 包名一模一样 编译下

    
    public class MainActivity extends AppCompatActivity {
        IMyAidlInterface mIMyAidlInterface;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_plugin);
            bindService();
        }
    
            ServiceConnection mServiceConnection = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    mIMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
                    System.out.println("==="+mIMyAidlInterface.getName());
                }
    
                @Override
                public void onServiceDisconnected(ComponentName name) {
    
                }
            };
    
            void bindService() {
                Intent intent = new Intent();
                intent.setAction("com.github.xch168.plugindemo.aidl.MyService");
                //从 Android 5.0开始 隐式Intent绑定服务的方式已不能使用,所以这里需要设置Service 启动的模块,注意这个 是服务端的项目包名 而不是services的包名
                intent.setPackage("com.github.xch168.plugindemo");
                boolean flag = bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
            }
    
            @Override
            protected void onDestroy() {
                super.onDestroy();
                unbindService(mServiceConnection);
            }
    }
    
    

    完事 就是这么简单

    相关文章

      网友评论

          本文标题:aidl例子

          本文链接:https://www.haomeiwen.com/subject/nlrnhktx.html