此次项目需求是系统程序需要执行放在sd卡的执行文件,由于系统用户没有访问sd卡权限,故需要将sd卡的执行程序通过客户端程序拷贝到system/bin目录下,系统程序在该目录下执行,因此需要用到aidl进程见通信
aidl是 Android Interface definition language的缩写,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口。
aidl需要客户端和服务端
一.服务端
IPTVAidl.aidl
interface IPTVAidl{
byte[] fileRead(String strFileName);
}
IPTVAidlService.java
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class IPTVAidlService extends Service{
private static final String TAG = "AIDLService";
private void Log(String str){
Log.i(TAG,"----------" + str + "----------");
}
@Override
public void onCreate() {
Log("service created");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Log("service started id = " + startId);
}
@Override
public IBinder onBind(Intent intent) {
Log("service on bind");
return mBinder;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
Log("service on unbind");
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
Log("service on rebind");
super.onRebind(intent);
}
private final IPTVAidl.Stub mBinder = new IPTVAidl.Stub() {
@Override
public byte[] fileRead(String strFileName) throws RemoteException {
InputStream is = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try{
File file = new File(strFileName);
is = new FileInputStream(strFileName);
byte[] b = new byte[(int) file.length()];
int temp;
while((temp = is.read(b)) != -1){
out.write(b, 0, temp);
}
}catch(Exception e){
Log(e.getMessage());
}finally{
if(is != null){
try{
is.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return out.toByteArray();
}
};
}
二.客户端
因为客户端要与服务端进行通信,所以客户端与服务端都要写aidl文件,并且名称内容必须一致
IPTVAidl.aidl
<span style="font-size:12px;">interface IPTVAidl{
byte[] fileRead(String strFileName);
}</span>
在需要实现通信的java类里加上
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
log("connect service");
mService = IPTVAidl.Stub.asInterface(service);
Message msg1 = Message.obtain(mWorkHandler, Commons.ZCTT.MSG_IPTVTEST_COPYFILE_START);
msg1.sendToTarget();
}
public void onServiceDisconnected(ComponentName className) {
log("disconnect service");
mService = null;
}
};
Intent aidlIntent = new Intent(AIDLACTION);
bindService(aidlIntent, mConnection, Context.BIND_AUTO_CREATE);
在需要实现通信的java类里需要触发的地方加上
mService.fileRead(Configs.IPTV_COPYFROMPATH);
三.需要注意的地方
1.客户端与服务端的aidl必须在同一个包下面
2.
Intent aidlIntent = new Intent(AIDLACTION);
这里的AIDLACTION必须与服务端AndroidManifest.xml文件写的service->intent-filter->action->android:name一致