首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

android callRemoteService 调用其余进程的service

2012-11-18 
androidcallRemoteService 调用其他进程的service创建一个进程服务.程序第一次运行的时候就创建.不需要界

android callRemoteService 调用其他进程的service

创建一个进程服务.程序第一次运行的时候就创建.不需要界面

要想其他进程能够跨进程的调用本进程的方法.就得使用跨进程访问的接口类型.只需将接口中类和方法的修饰符去掉就行.然后把接口类编程aidl类型

服务也业务代码:

package com.example.callremoteservice;import com.example.remoteservice.IServcice;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.view.View;/** * 访问外部服务.要知道对方服务的action,和可以调用服务接口的adil文件以及adil文件的包名<br> * 在本地程序创建调用服务的adil文件的包,并添加外部服务的adil文件,系统会自动在gen目录下创建该adil文件接口java文件<br> * 总结:<br> * 访问本进程中的service,需要用到bindService()方法.(cz23_serverlifecycle)<br> *  * 1创建一个服务,该服务中要有能被调用的方法;<br> * 2:定义一个借口IService, 接口里面的抽象方法去调用服务中的方法 ;<br> * 3:定义一个MyBinder对象.继承binder类,并实现IService接口,在onBind方法中返回MyBinder对象;<br> * 4:在activity中通过bindService ()绑定一个服务;<br> * 5:创建一个MyConn实现ServiceConnection接口 ,服务绑定成功后执行接口中的onServiceConnected()方法;<br> * 6:onServiceConnected ()方法的IBinder参数就是IService类型的,强制转换为IService;<br> * 7:调用ISservice中方法<br> * <br> * 访问 外部进程中的service,需要用到aidl(android interface definition language)(在编号24的两个例子)<br> * 1创建一个服务,该服务中要有能被调用的方法;<br> * 2:定义一个借口IService, 接口里面的抽象方法去调用服务中的方法,去掉定义接口和接口中方法的修饰符,把这个接口的扩展名该为.aidl,;<br> * 3:定义一个MyBinder对象,继承编译器根据IService.aidl在gen中创建的IService类中的Sutb类, * 在onBind方法中返回MyBinder对象<br> * 4:在调用服务的工程中创建包,包名要与被调用服务工程中对应aidl文件所在的包名一样.并复制被调用工程对应的aidl文件到本地对应aidl文件包中<br> * 5:在activity中通过bindService ()绑定一个服务;<br> * 6:创建一个MyConn实现ServiceConnection接口 ,服务绑定成功后执行接口中的方法;<br> * 7:在实现接口中的onServiceConnected()方法调用IServcice.Stub.asInterface()方法. * 将onServiceConnected的IBinder参数转换成IService类型<br> * 8:调用IService中的方法(调用服务中的方法), *  * @author Administrator *  */public class MainActivity extends Activity {private IServcice iServcice;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent intent = new Intent();intent.setAction("com.example.remoteservice");// 隐式意图,指定访问服务的action,就是被调用服务进程值注册服务的时候指定的action的值bindService(intent, new MyConn(), Context.BIND_AUTO_CREATE);// 通过隐式意图绑定到外部服务.参数2是服务绑定成功后的一个回调类.通过他可以获取外部服务对外提供数据的对象}public void click(View view) {try {iServcice.callMethodInService();} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}class MyConn implements ServiceConnection {@Override/** * 参数IBinder就是绑定被调用的服务执行onBind的返回值 */public void onServiceConnected(ComponentName arg0, IBinder service) {iServcice = IServcice.Stub.asInterface(service);// 调用外部进程中service的转换方法}@Overridepublic void onServiceDisconnected(ComponentName arg0) {// TODO Auto-generated method stub}}}




热点排行