Android经过Aidl调用Service实例

最近在上Android课程,如今我懒得备课了,直接拿博客来说好了!java


Aidl访问Service实例:android


Android中Activity与Service是属于两个不一样的进程的,而两个进程之间的通信除了能够用广播以外,最完美的解决方案就是使用AIDL。数组

AIDL(AndRoid接口描述语言)是一种借口描述语言; 编译器能够经过aidl文件生成一段代码,经过预先定义的接口达到两个进程内部通讯进程的目的. 若是须要在一个Activity中, 访问另外一个Service中的某个对象, 须要先将对象转化成AIDL可识别的参数(多是多个参数), 而后使用AIDL来传递这些参数, 在消息的接收端, 使用这些参数组装成本身须要的对象.  
app

实例:ide

一、建立包名:com.example.androidserviceaidltest.service工具

二、在新建立的目录下建立一个文件:IAidlMyService.aidl,并写入如下内容:布局

package com.example.androidserviceaidltest.service;

interface IAidlMyService {
	String getValue();
	Map getBook();
}

 

这里须要注意几个问题:开发工具

  1. .aidl文件中不能出现如public、private、static等这样的修饰符this

  2. .aidl文件后缀必需是.aidlspa

  3. 支持全部的java语言的基本数据类型,好比int, long, char, Boolean 等等。


这其实就是定义一个Aidl接口文件,此时开发工具会在gen目录下生成一个对应的IAidlMyService.java文件,并成生了相应的代码。

结构以下图所示:


四、定义一个Service类AidlMyService.java,在com.example.androidserviceaidltest.service目录下,继承android.app.Service

并定义一个内部类AidlMyServiceImpl,继承IAidlMyService.Stub,并实现getView与getBook两个方法.

AidlMyService类中的onBind()会在绑定时调用,该方法中须要返回一个AidlMyServiceImpl的实例。

 

package com.example.myaidlservicetest.services;
import java.util.HashMap;
import java.util.Map;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AidlMyService extends Service {
 @Override
 public IBinder onBind(Intent arg0) {
  //返回远程服务的实例
  return new AidlMyServiceImpl();
 }
 
 /**
  * 定义一个远程的服务类
  * @author MingliC
  */
 public class AidlMyServiceImpl extends IAidlMyService.Stub{
  @Override
  public String getValue() throws RemoteException {
   return "这是来自Aidl的数据";
  }
  @Override
  public Map<String, String> getBook() throws RemoteException {
   
   Map<String, String> map = new HashMap<String, String>();
   map.put("name", "《天龙八部》");
   map.put("anthor", "金庸");
   
   return map;
  }
 }
}

 

Activity中实现绑定:

package com.example.androidserviceaidltest;

import com.example.androidserviceaidltest.service.IAidlMyService;
import com.example.androidserviceaidltest.service.MyService;

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

public class MainActivity extends Activity {
	
	private Context mContext;
	private IAidlMyService myService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
	}
	
	/**
	 * 点击启动服务时按钮时调用
	 * @param view
	 */
	public void clickStartService(View view){
		Intent intent = new Intent(this, MyService.class);
		this.startService(intent);
		Toast.makeText(this, "start service", Toast.LENGTH_SHORT).show();
	}
	
	/**
	 * 点击绑定服务时调用
	 * @param view
	 */
	public void clickBindService(View view){
		bindService(
				new Intent("com.example.androidserviceaidltest.service.AidlMyService"), 
				serviceConnection, 
				Context.BIND_AUTO_CREATE
		);
		Toast.makeText(mContext, "bund service", Toast.LENGTH_SHORT).show();
	}
	
	/**
	 * 点击获取数据时调用
	 * @param view
	 */
	public void clickGetValue(View view){
		try {
			Toast.makeText(mContext,myService.getValue(), Toast.LENGTH_SHORT).show();
			Toast.makeText(mContext,myService.getBook().get("name").toString(), Toast.LENGTH_SHORT).show();
		} catch (RemoteException e) {
			e.printStackTrace();
			Toast.makeText(mContext,"获取数据失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	private ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// 得到服务对象 
			myService = IAidlMyService.Stub.asInterface(service); 
			Toast.makeText(mContext, "服务绑定成功", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			//当断开绑定时
			Toast.makeText(mContext, "服务断开", Toast.LENGTH_SHORT).show();
		} 

	}; 

	@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;
	}

}

 


六、布局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickBindService"
        android:text="绑定服务" />
        
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clickGetValue"
        android:text="获取数据" />

</LinearLayout>

 


七、Service是Android四大组件之一,因上还须要到AndroidManifest.xml中向系统注册service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidserviceaidltest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidserviceaidltest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!-- 向系统注册serivce -->
       <service android:name="com.example.androidserviceaidltest.service.AidlMyService">
           <intent-filter>
               <action android:name="com.example.androidserviceaidltest.service.AidlMyService"/>
           </intent-filter>
       </service>

    </application>

</manifest>

 


八、不出意外的话,你应该能够运行了!你须要先点击绑定服务,当绑定成功后会Toast中“绑定成功”

当绑定成功后,你就能够点击“获取数据”,会Toast出两个数据,"来自Aidl的数据..."和“《你们好》”。

至此,你已大功告成!

相关文章
相关标签/搜索