2010. 8. 16. 19:39

Local Service and Remote Service ( AIDL Service )

안드로이드에는 두종류의 서비스가 있습니다.

* 로컬 서비스 (local service)

애플리케이션내에만 서비스 하는 것으로 다른 애플리케이션에서는 접근할 수 없습니다. 로컬서비스는 백그라운드 작업을 쉽게 구현하도록 하기 위해서입니다. 

* 원격 서비스 (remote service)

원격서비스는 애플리케이션간에 Interprocess Communication 을 지원하기 위한 것입니다. 이를 지원하기 위해 AIDL (Android Interface Definition Lanaguage)를 사용하기 때문에 AIDL Service 라고도 부릅니다. 

에제를 통해서 살펴보는게 나을 것입니다.

로컬 서비스 예제

아래 첨부는 이클립스 프로젝트 입니다.


BackgroundService.java

package com.sskk.sample.localservicetest.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.sskk.sample.localservicetest.MainActivity;
import com.sskk.sample.localservicetest.R;

public class BackgroundService extends Service
{
	private NotificationManager notificationMgr;
	@Override
	public void onCreate() {
		super.onCreate();
		notificationMgr =(NotificationManager)getSystemService(
				NOTIFICATION_SERVICE);
		displayNotificationMessage("starting Background Service");
		Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
		thr.start();
	}
	class ServiceWorker implements Runnable
	{
		public void run() {
			// do background processing here...
			// stop the service when done...
			// BackgroundService.this.stopSelf();
		}
	}
	@Override
	public void onDestroy()
	{
		displayNotificationMessage("stopping Background Service");
		super.onDestroy();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	private void displayNotificationMessage(String message)
	{
		Notification notification = new Notification(R.drawable.note,
				message,System.currentTimeMillis());
		PendingIntent contentIntent =
			PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
		notification.setLatestEventInfo(this, "Background Service",message,
				contentIntent);
		notificationMgr.notify(R.id.app_notification_id, notification);
	}
}


원격 서비스 예제



1. 간단한 AIDL 구현 예제

IStockQuoteService.aidl

package com.sskk.sample.service;

interface IStockQuoteService {
	double getQuote(String ticker);
}

StockQuoteService2.java

package com.sskk.sample.service;

import com.sskk.sample.service.IStockQuoteService;
import com.sskk.sample.service.IStockQuoteService.Stub;

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

public class StockQuoteService extends Service {
	private static final String TAG = "StockQuoteService";
	
	public class StockQuoteServiceImple extends IStockQuoteService.Stub {

		@Override
        public double getQuote(String ticker) throws RemoteException {
	        Log.v(TAG, "종목 " + ticker + "에 대해 getQuote() 호출됨");
	        return 20.0;
        }
		
	}

	@Override
    public IBinder onBind(Intent p_intent) {
	    Log.v(TAG, "onBind 호출됨");
	    return new StockQuoteServiceImple();
    }

	@Override
    public void onCreate() {
	    super.onCreate();
	    
	    Log.v(TAG, "onCreate 호출됨");
    }

	@Override
    public void onDestroy() {
	    super.onDestroy();
	    
	    Log.v(TAG, "onDestroy 호출됨");
    }

	@Override
    public void onStart(Intent p_intent, int p_startId) {
	    super.onStart(p_intent, p_startId);
	    
	    Log.v(TAG, "onStart 호출됨");
    }
	
	
}

2. 객체를 전달하는 AIDL 예제

Person.aidl

package com.sskk.sample.service;
parcelable Person;
Person.java

package com.sskk.sample.service;

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {
	private int mAge;
	private String mName;
	public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {

		@Override
        public Person createFromParcel(Parcel in) {	        
	        return new Person(in);
        }

		@Override
        public Person[] newArray(int size) {
	        return new Person[size];
        }
		
	};
	
	public Person() {
		
	}
	
	private Person(Parcel in) {
		readFromParcel(in);
	}
	
	public void readFromParcel(Parcel in) {
		mAge = in.readInt();
		mName = in.readString();
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel out, int flags) {
		out.writeInt(mAge);
		out.writeString(mName);
	}
	
	public int getAge() {
		return mAge;
	}
	
	public void setAge(int age) {
		mAge = age;
	}
	
	public String getName() {
		return mName;
	}
	
	public void setName(String name) {
		mName = name;
	}

}

StockQuoteService2.aidl

package com.sskk.sample.service;
import com.sskk.sample.service.Person;


interface IStockQuoteService2 {
	String getQuote(in String ticker, in Person requester);
}
StockQuoteService2.java

package com.sskk.sample.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import com.sskk.sample.aidltest.NotiActivity;
import com.sskk.sample.aidltest.R;

public class StockQuoteService2 extends Service {
	private NotificationManager mNotificationManager;
	
	public class StockQuoteServiceImple2 extends IStockQuoteService2.Stub {

		@Override
        public String getQuote(String ticker, Person requester) throws RemoteException {
	        // TODO Auto-generated method stub
	        return "안녕하세요, " + requester.getName() + "!" + ticker + "의 주가는 20.0 입니다.";
        }				
	}

	@Override
	public void onCreate() {
	    super.onCreate();
	    
	    mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	    displayNotificationMessage("onCreate 가 호출됨");	    	    
	}
	
	@Override
	public void onDestroy() {
		displayNotificationMessage("onDestroy 가 호출됨");
	    super.onDestroy();
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
	    super.onStart(intent, startId);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
	    displayNotificationMessage("onBind 가 호출됨");
	    return new StockQuoteServiceImple2();
	}		
	
	private void displayNotificationMessage(String message) {
		Notification notification = new Notification(R.drawable.note, message, System.currentTimeMillis());
		
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, NotiActivity.class), 0);
		notification.setLatestEventInfo(this, "StockQuoteService2", message, contentIntent);
		
		mNotificationManager.notify(R.id.app_notification_id, notification);
	}
	
}

3. AndroidMnifiest.xml 에 서비스 등록하기


	
		
			
				
			
		
		
			
				
			
		
	
 
참고: Pro Android 2