二、实现AIDL服务的步骤
1. 编写AIDL文件
2. 如果aidl文件的内容是正确的,会自动生成一个Java接口文件(*.java)。
3. 建立一个服务类(Service的子类)。
4. 实现由aidl文件生成的Java接口。
5. 在AndroidManifest.xml文件中配置AIDL服务, 添加<action>标签的android:name,以便客户端使用隐式Intent启动服务
6、客户端
三、编写AIDL文件
Android接口定义语言——LocalService.aidl
package com.jereh.remote;interface LocalService{String getLocal();}
四、Remote应用实现
1、编写MyRemoteService
public class MyRemoteService extends Service {@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn new MyRemoteServiceImpl();}private class MyRemoteServiceImpl extends LocalService.Stub{@Overridepublic String getLocal() throws RemoteException {// TODO Auto-generated method stubreturn "烟台杰瑞教育";}}}2、AndroidManifest.xml配置
<service android:name="com.jereh.retmote.MyRemoteService"android:process="remote"><intent-filter><action android:name="com.jereh.remote_service"/></intent-filter> </service>五、客户端实现
同样会自动生成LocalService.java 代码
2、MainActivity代码:
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void startService(View view){Intent service=new Intent("com.jereh.remote_service");super.bindService(service, conn, Context.BIND_AUTO_CREATE);}public void showInfo(View view){try {local=service.getLocal();Log.d("jereh", local);Toast.makeText(this, "您已进入"+local,Toast.LENGTH_LONG).show();} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}privateLocalService service;privateString local;private ServiceConnection conn=new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName arg0) {}@Overridepublic void onServiceConnected(ComponentName name, IBinder binder) {// TODO Auto-generated method stub// 获取远程Service的onBinder方法返回的对象代理service=LocalService.Stub.asInterface(binder);}};@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="启动远程服务" android:onClick="startService" /> <Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="查看信息" android:onClick="showInfo" /></LinearLayout>以上所述就是本文给大家介绍的Android应用程序四大组件之使用AIDL如何实现跨进程调用Service,希望大家喜欢。