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的數據..."和「《你們好》」。

至此,你已大功告成!

相關文章
相關標籤/搜索