android 绑定下载服务,Android绑定远程服务

方法:

c186787396974a3031d48d64ce76557b.png

服务项目目录结构:

调用方项目目录结构:

1f6503e1b0c89090ba867a39bcb2abda.png

fb3c0c4849c9c7218e324e4050b9ff2a.png

Iservice.aidl文件 android interface definition language 安卓用于项目间使用同一接口的方式:

package com.pas.payservice;

interface IService

{

void callpay();

}

全为public所以不可以加修饰符,

调用方需要拷贝此文件及包结构

Service核心:

public IBinder onBind(Intent arg0)

{

Log.i(tag, "远程支付服务:onBind");

return new MyBinder();

}

private class MyBinder extends IService.Stub

{

@Override

public void callpay()

{

pay();

}

}

调用方主AC:注意与调用本地服务的api区别

package com.pas.useage;

import com.pas.payservice.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 binder;

private MyConn conn;

@Override

protected void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

intent = new Intent();

intent.setAction("com.pas.alipay");

}

@Override

public 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;

}

public void bind(View v)

{

conn = new MyConn();

startService(intent);

bindService(intent, conn, BIND_AUTO_CREATE);

}

private class MyConn implements ServiceConnection

{

@Override

public void onServiceConnected(ComponentName name, IBinder service)

{

binder = IService.Stub.asInterface(service);

}

@Override

public void onServiceDisconnected(ComponentName name)

{

// TODO Auto-generated method stub

}

}

public void call(View v)

{

try

{

binder.callpay();

} catch (RemoteException e)

{

e.printStackTrace();

}

}

@Override

protected void onDestroy()

{

try

{

if (conn != null)

{

unbindService(conn);

}

} catch (Exception e)

{

// TODO: handle exception

}

super.onDestroy();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值