您的位置:首页 > 移动开发 > Android开发

Android使用aidl来绑定远程服务

2016-02-18 16:15 411 查看
 绑定远程服务流程
1、在activity中绑定调用bindService去绑定服务
bindService(intent, conn, flags)
2、在服务里面 需要重写方法  onBind   在服务被绑定的时候需要返回一个代理人,调用返回一个IBinder,这个代理人必须要实现一个方法,这个方法能否调用服务中的方法
3、在Activity中onServiceConnected中得到代理人
4、调用代理人中的方法。
 
案例:
一个应用:
package com.example.RemoteService;

import com.example.AlipayService.IService;

import android.os.Bundle;

import android.os.IBinder;

import android.os.RemoteException;

import android.app.Activity;

import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.view.Menu;

import android.view.View;

public class MainActivity extends Activity {

 private Intent intent;

 private IService iservice;

 @Override

 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

   intent = new Intent();

  intent.setAction("com.eastmoney.Alipay");

 }

 public void bind(View view){ 

  bindService(intent, new Myconn(), BIND_AUTO_CREATE);

  

 }

 private class Myconn implements ServiceConnection{

  @Override

  public void onServiceConnected(ComponentName name, IBinder service) {

   //强制內型转换为IService的接口类型

   iservice = IService.Stub.asInterface(service) ;

  

  }

  @Override

  public void onServiceDisconnected(ComponentName name) {

 

  }

  

 }

 public void call(View view){

  try {

   iservice.callmethodInService();

  } catch (RemoteException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

 }

 

}

 

package com.example.AlipayService;

 interface IService {

  void callmethodInService();

}

 

 
 

package com.example.AlipayService;

 interface IService {

  void callmethodInService();

}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: