在网上看了好几篇关于AIDL的入门的文章终于写出了我的第一个AIDL入门例子,特此发帖
—— 每个程序员都有一颗开源的心
服务端:
1.服务端创建aidl,build project
package com.fafa.aidlserver;
interface RemoteService {
String getInfor(String s);
}
2.创建service
package com.fafa.aidlserver;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
/**
* Created by ZhouBing on 2017/8/14.
*/
public class MyService extends Service{
private final IBinder binder = new RemoteService.Stub() {
@Override
public String getInfor(String s) throws RemoteException {
return "我是Service返回的字符串";
}
};
@Override
public IBinder onBind(Intent intent) {
Log.d("aidl", "aidlService--------------onBind");
return binder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("aidl", "aidlService--------------onCreate");
}
}
3.暴露服务
<service android:name=".MyService">
<intent-filter>
<action android:name="com.fafa.aidlserver.MyService"/>
</intent-filter>
</service>
客户端
1.拷贝aidl自动生成的接口文件到客户端,注意一定要连包一起拷过去,不然出错?
2.绑定服务
package com.fafa.aidlclient;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.fafa.aidlserver.RemoteService;
public class MainActivity extends AppCompatActivity {
public final static String TAG = "aidl";
private RemoteService myInterface;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myInterface = RemoteService.Stub.asInterface(service);
Log.i(TAG, "连接Service 成功");
try {
String s = myInterface.getInfor("我是Activity传来的字符串");
Log.i(TAG, "从Service得到的字符串:" + s);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "连接Service失败");
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setAction("com.fafa.aidlserver.MyService");
intent.setPackage("com.fafa.aidlserver");
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
}
}
安装服务端,运行客户端
这篇博客可以看下 http://blog.csdn.net/wuzhipeng1991/article/details/40376507
代码 传送门