您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页aidl的使用

aidl的使用

来源:化拓教育网

aidl

package xyz.liut.myaidltest;

interface IService {
      int plus(int a,int b);
}

server端代码

public class MyServiceTest extends Service {
    private IService.Stub stub = new IService.Stub() {
        @Override
        public int plus(int a, int b) throws RemoteException {
            return a + b;
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return stub;
    }
}
        <service
            android:name=".MyServiceTest"
            android:exported="true">
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="xyz.liut.aidltest" />
            </intent-filter>
        </service>

client端

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private IService iService;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iService = IService.Stub.asInterface(service);
            Log.e(TAG, "onServiceConnected: " + service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            iService = null;
            Log.e(TAG, "onServiceDisconnected: " + name);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setPackage("xyz.liut.myaidltest");
        intent.setAction("xyz.liut.aidltest");
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    public void test(View view) {
        try {
            if (iService == null) {
                Toast.makeText(this, "未绑定远程服务", Toast.LENGTH_SHORT).show();
                return;
            }
            int sum = iService.plus(1, 2);
            new AlertDialog.Builder(this)
                    .setTitle("sum")
                    .setMessage(Integer.toString(sum))
                    .setPositiveButton("ok", null)
                    .show();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务