Andriod Service 远程

来源:互联网 发布:国际象棋对弈软件下载 编辑:程序博客网 时间:2024/05/22 06:46
        远程Service是指跨进程的调用服务的方法,主要实现方法如下:

第一部分:建立一个service

(1)建立一个AIDL文件;

package com.example.servicetest;  interface MyAIDLService {      int plus(int a, int b);     }
(2)创建一个服务,实现AIDL文件中的方法;

public class MyService extends Service {public static final String TAG = "MyService";  @Overridepublic void onCreate() {super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();}@Overridepublic IBinder onBind(Intent arg0) {return mBinder;} MyAIDLService.Stub mBinder = new Stub() {           @Override          public int plus(int a, int b) throws RemoteException {              return a + b;          }      };  }
(3)将service配置成为远程;

      <service             android:name="com.example.servicetest.MyService"            android:process=":remote"         >              <intent-filter>              <action android:name="com.example.servicetest.MyAIDLService"/>          </intent-filter>          </service>     
运行;

第二部分:建立一个测试client调用远程服务

(1)新建一个新的android app程序;
(2)把MyAIDLService.AIDL文件,带着包名拷贝到client测试程序中;
(3)编写测试程序,测试远程调用服务

public class MainActivity extends Activity { private MyAIDLService myAIDLService;     private ServiceConnection connection = new ServiceConnection() {             @Override          public void onServiceDisconnected(ComponentName name) {          }            @Override          public void onServiceConnected(ComponentName name, IBinder service) {              myAIDLService = MyAIDLService.Stub.asInterface(service);              try {                  int result = myAIDLService.plus(10, 90);                  Log.d("TAG", "result is " + result);                } catch (RemoteException e) {                  e.printStackTrace();              }          }    };    @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);     Button bindService = (Button) findViewById(R.id.bind_service);          bindService.setOnClickListener(new OnClickListener() {              @Override              public void onClick(View v) {                  Intent intent = new Intent("com.example.servicetest.MyAIDLService");                  bindService(intent, connection, BIND_AUTO_CREATE);              }          }); }
个人测试,好用。

总结


(1)创建一个服务,这个服务里面有一个要被调用的方法;
(2)定义个接口MyAIDLService,接口里面的抽象方法就是去调用service里面的方法;
         把.java的后缀名改成aidl 把接口里面定义的访问权限的修饰符都给删除;
(3)定义一个mybinder对象 extends MyAIDLService.Stub,
         在onbind方法里面把mybinder返回回去;
(4)在activity里面 通过bindserver方法开启服务;
(5)创建出一个我们Mycon 实现ServiceConnetion接口 onserviceConnected的方法
          这个方法会有一个参数,这个参数就是 Mybinder的对象;
(6)MyAIDLService = MyAIDLService.stub.asInterface(myBinder)
(7)调用MyAIDLService的方法。 

0 0
原创粉丝点击