标签:
前面总结了程序间共享数据,可以使用ContentProvider也可以使用SharedPreference,那么进程间怎么共享内存呢?Android系统中的进程之间不能共享内存,因此,需要提供一些机制在不同进程之间进行数据通信。
为了使其他的应用程序也可以访问本应用程序提供的服务,Android系统采用了远程过程调用(Remote Procedure Call,RPC)方式来实现。与很多其他的基于RPC的解决方案一样,Android使用一种接口定义语言(Interface Definition Language,IDL)来公开服务的接口。我们知道4个Android应用程序组件中的3个(Activity、BroadcastReceiver和ContentProvider)都可以进行跨进程访问,另外一个Android应用程序组件Service同样可以。因此,可以将这种可以跨进程访问的服务称为AIDL(Android Interface Definition Language)服务。
interface ITestInterface { //获取进程ID int getProcessId(); //处理字符串 String dealString( String srcString); //字符串追加 String appendString( String srcString); void addPerson(in Person person); List<Person> getPersons(); }
aidl语法解说:
private final ITestInterface.Stub mBinder = new ITestInterface.Stub() { public int getProcessId(){ Log.e("TestService","TestService Thread: " + Thread.currentThread().getName()); Log.e("TestService","TestService getProcessId()"); return android.os.Process.myPid(); } //处理字符串 public String dealString( String srcString) { return srcString+srcString; } //字符串追加 public String appendString( String srcString) { return srcString+srcString; }
private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.e("TestService","TestService onServiceDisconnected()"); } @Override public void onServiceConnected(ComponentName name, IBinder service) { iTestInterface = ITestInterface.Stub.asInterface(service); try { Log.e("TestService","TestService onServiceConnected()"); int remoteId=iTestInterface.getProcessId(); Log.e("TestService","TestService remoteId---->"+remoteId); int currentPid = android.os.Process.myPid(); Log.e("TestService","TestService currentPid---->"+currentPid); Log.e("TestService","TestService dealString---->"+iTestInterface.dealString("Remote Service")); Log.e("TestService","TestService appendString---->"+iTestInterface.appendString("Remote Service")); } catch (RemoteException e) { e.printStackTrace(); } } };
int remoteId=iTestInterface.getProcessId(); Log.e("TestService","TestService remoteId---->"+remoteId); int currentPid = android.os.Process.myPid(); Log.e("TestService","TestService currentPid---->"+currentPid); Log.e("TestService","TestService dealString---->"+iTestInterface.dealString("Remote Service")); Log.e("TestService","TestService appendString---->"+iTestInterface.appendString("Remote Service"));
声明:
<service android:name=".TestService" android:enabled="true" android:exported="true" android:label="remoteService" android:process=":remote"> <intent-filter android:priority="1000"> <category android:name="android.intent.category.DEFAULT" /> <action android:name="com.whoislcj.testaidl.TestService" /> </intent-filter> </service>
绑定:
Intent intent = new Intent("com.whoislcj.testaidl.TestService"); intent.setPackage(getPackageName());//这里你需要设置你应用的包名 bindService(intent, connection, Context.BIND_AUTO_CREATE);
解绑:
unbindService(connection);
标签:
原文地址:http://www.cnblogs.com/whoislcj/p/5509868.html