关于AIDL的入门笔记

 好久没写BLOG了,作为一个程序员,一个要多写BLOG啊(对自已的要求)

之前写过很多次AIDL的例子,但总是忘了,这次就写下来吧

FirstBlood,建一个project,叫AIDLService,定义一个AIDL文件(在包 com.example.haha中)

  

package com.example.haha;  
interface IDownService {  
    //这里不需要加权限修饰符(就如public.private之类的)
    void downLoad(String path);  
    }  

   很明显这是一个接口,如果您是用eclipse的话,它会在gen里面自动生成一个IDownService.java文件。

    然后实现这个接口,让其他地方通过接口来调用这个实现的方法

扫描二维码关注公众号,回复: 633330 查看本文章
package com.example.aidl;

import com.example.haha.IDownService;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

/**
 * @author cfuture_小智
 * @Description 远程服务接口的实现
 */
public class DownService extends Service {

        //这里为什么是new 一个Stub我也不太清楚
	private IDownService.Stub binder = new IDownService.Stub() {

		@Override
		public void downLoad(String path) throws RemoteException {
			Log.v("AIDL", this.getClass().getName()
					+ "---downRemoteException:++path" + path);
		}
	};

	//在远程调用的时候,将会得到binder(事实它是IDownService的实现)这个对象
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

}

 最后在AndroidManifest.xml定义一下service,因为你在另一个项目里只能通过隐性Intent打开服务。

        <service android:name="com.example.aidl.DownService" >
            <intent-filter>
                <action android:name="com.cfuture.xiaozhi.aidltest" />
            </intent-filter>
        </service>

到这里服务端的方法都已经做好了。

接下来建一个客户端AIDLClient来调用服务端的方法。

当然,你还要把那个AIDL文件,从AIDLService项目中连包一起复制过来。

像图片这样:



 

再写你的调用代码

package com.cfuture.xiaozhi.example.aidlclient;

import com.example.haha.IDownService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.Menu;

public class MainActivity extends Activity {
	private IDownService downService;
	private ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			downService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
                         //在这里就可以得到DownServce的实例了,这时候你想干嘛就干嘛
			downService = IDownService.Stub.asInterface(service);
			try {
				downService.downLoad("http://google.com");
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent intent = new Intent("com.cfuture.xiaozhi.aidltest");
		// 绑定到远程服务
		bindService(intent, serviceConnection, 1);
	}

}

 OK了,这样子就行了

猜你喜欢

转载自xiaozhi6156.iteye.com/blog/1963437