Android通过Aidl调用Service实例

最近在上Android课程,现在我懒得备课了,直接拿博客来讲好了!


Aidl访问Service实例:


Android中Activity与Service是属于两个不同的进程的,而两个进程之间的通讯除了可以用广播之外,最完美的解决方案就是使用AIDL。

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

实例:

1、创建包名:com.example.androidserviceaidltest.service

2、在新创建的目录下创建一个文件:IAidlMyService.aidl,并写入以下内容:

package com.example.androidserviceaidltest.service;

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

 

这里需要注意几个问题:

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

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

  3. 支持所有的java语言的基本数据类型,比如int, long, char, Boolean 等等。


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

结构如下图所示:

130336_Ts8Y_162091.png


4、定义一个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;
	}

}

 


6、布局文件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>

 


7、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>

 


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

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

至此,你已大功告成!



转载于:https://my.oschina.net/minglic/blog/186853

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值