进程间通信——AIDL&IPC

作者:追风剑情 发布于:2016-8-13 16:39 分类:Android

Android接口定义语言(AIDL)

进程间通信(IPC)

示例一:Activity与Service之间利用IPC机制通信

一、创建IDateTimeService.aidl

package com.test.androidtest;

interface IDateTimeService {
	String getCurrentDateTime(in String format);
}

 

二、创建DateTimeService.java

package com.test.androidtest;

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

public class DateTimeService extends Service{

	IBinder dateTimeService = new IDateTimeService.Stub() {
		@Override
		public String getCurrentDateTime(String format) throws RemoteException {
			
			return "1900-05-10";
		}
	};
	
	@Override
	public IBinder onBind(Intent intent) {
		return dateTimeService;
	}
}

 

三、创建MainActivity.java

package com.test.androidtest;

import android.app.Activity;
import android.os.IBinder;
import android.os.Bundle;
import android.os.RemoteException;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;

public class MainActivity extends Activity
{
	Intent intent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main);
		
		//启动时间服务
		intent = new Intent(MainActivity.this, DateTimeService.class);
		bindService(intent, connection, Context.BIND_AUTO_CREATE);
	}
	
	private ServiceConnection connection = new ServiceConnection(){
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.d("test", "连接DateTimeService成功!");
			IDateTimeService dateTimeService = IDateTimeService.Stub.asInterface(service);
			Log.d("test", "service="+dateTimeService);
			try {
				Log.d("test", "时间="+dateTimeService.getCurrentDateTime(""));
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			startService(intent);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.d("test", "连接DateTimeService失败!");
		}	
	};
}

 

运行测试

1111111.png

 

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号