android 绑定远程服务

aidl :  android interface defination language  安卓接口定义语言.
提供两个应用程序之间交互的接口
IPC: inter process communication  进程间通讯


首先创建一个远程服务的程序,创建一个Service,在程序中配置它的action,然后创建aidl接口

Service代码:

public class RemoteSerivce extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return new MyBinder();
	}

	private class MyBinder extends IService.Stub {

		@Override
		public void callInServiceMethod() throws RemoteException {
			serviceMethod();
		}
	}

	private void serviceMethod() {
		System.out.println("远程服务里面的方法");
	}
}

配置文件的代码:

        <service android:name="com.alan.remodeservice.RemoteSerivce" >
            <intent-filter>
                <action android:name="aaa.bbb.ccc.remote" />
            </intent-filter>
        </service>

接着创建一个调用远程服务的方法的程序:

activity代码:

public class MainActivity extends Activity {
	private Button mRemoteButton;
	private Button mRemoteMethod;
	private IService iService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mRemoteButton = (Button) findViewById(R.id.button1);
		mRemoteMethod = (Button) findViewById(R.id.button2);

		// 绑定远程服务
		mRemoteButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				// 远程配置的action是什么要与之对应
				intent.setAction("aaa.bbb.ccc.remote");
				bindService(intent, new ServiceConnections(), BIND_AUTO_CREATE);
			}
		});

		// 调用远程服务的方法
		mRemoteMethod.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					iService.callInServiceMethod();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

	}

	class ServiceConnections implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// 这行是重点
			iService = IService.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {

		}

	}
}

在这里最重要的是IService.aidl文件,在远程当中的IService.aidl文件的包名与调用远程方法的程序的包名必须要一致,两个程序都必须要有IService.aidl这个文件

IService.aidl代码:

package com.alan.remodeservice;

    interface IService {

	 void callInServiceMethod();
}
这里提醒一下,接口和方法都不能声明为public的,会报错。因为这里的接口默认都是全局可见的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值