AIDL的在Android Studio中的使用

  1. 创建一个AIDL

  2. 进行gradle构建在这里插入图片描述成功之后会在此文件夹下出现此文件,可以在此aidl中自定义方法。

  3. 创建一个service
    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    import android.os.RemoteException;

    import com.henau.henau.examsystem.IMyAidlInterface;

    public class AIDLService extends Service {

    IMyAidlInterface.Stub stub=new IMyAidlInterface.Stub() {
    @Override
    public void basicTypes(int anInt, long aLong, boolean aBoolean,
    float aFloat, double aDouble, String aString) throws RemoteException {
    }

    @Override
    public String getName(String name) throws RemoteException {
        return name+"hahah";
    }
    

    };
    @Override
    public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    return stub;
    }
    }
    此service中创建一个IMyAidlInterface对象并实现其中的方法,其中getName为自定义方法.

4.在Activity中进行绑定Service通过bindService方法

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Toast;

import com.henau.henau.examsystem.IMyAidlInterface;
import com.henau.henau.examsystem.R;
import com.henau.henau.examsystem.Service.AIDLService;

public class AIDL extends AppCompatActivity implements View.OnClickListener {

IMyAidlInterface iMyAidlInterface;
private ServiceConnection mServiceConnect=new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_aidl);
    findViewById(R.id.start).setOnClickListener(this);
    bindService(new Intent(AIDL.this, AIDLService.class),mServiceConnect,BIND_AUTO_CREATE);
}

@Override
public void onClick(View v) {
    switch (v.getId())
    {
        case R.id.start:
            try {
                String s = iMyAidlInterface.getName("xiaoliang");
                Toast.makeText(AIDL.this,s,Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();

            }
    }
}

}

通过iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);此方法得到IMyAidlInterface对象,通过此对象进行自动调用Service中的方法.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值