在Android Studio中使用AIDL
2018-04-09 本文已影响0人
留给时光吧
1. 首先创建aidl文件夹,位于main目录下,和Java和res同级,如下:
2. 在aidl目录中创建需要的aidl文件,通过右键new--AIDL--AIDL file可以很方便的创建:
package com.app.cheny.aidl;
interface IMyAidlInterface {
String fun();
}
3. 然后手动编译一下,Build -- Make Module ...
若成功的话会在build目录下生成这样一个文件:
4. 最后正常写服务端和客户端代码即可,如下
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return new IMyService();
}
public class IMyService extends IMyAidlInterface.Stub {
@Override
public String fun() throws RemoteException {
return "Hello world";
}
}
}
public class MainActivity extends AppCompatActivity {
private IMyAidlInterface mService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(getApplicationContext(),MyService.class);
bindService(intent,connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
public void get(View view) {
try {
((Button)view).setText(mService.fun());
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
另外如果AIDL中涉及需要序列化的对象,需要这样操作,若序列化类如下:
public class Item implements Parcelable {
public String tag;
Item(String tag){
this.tag = tag;
}
protected Item(Parcel in) {
tag = in.readString();
}
public static final Creator<Item> CREATOR = new Creator<Item>() {
@Override
public Item createFromParcel(Parcel in) {
return new Item(in);
}
@Override
public Item[] newArray(int size) {
return new Item[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(tag);
}
}
对应的aidl文件如下,其中parcelable是小写的:
package com.app.cheny.aidl;
parcelable Item ;
修改IMyAidlInterface文件如下,注意import内容:
package com.app.cheny.aidl;
import com.app.cheny.aidl.Item;
interface IMyAidlInterface {
Item fun();
}
剩下的就在对应Java文件中修改即可。