본문 바로가기
프로그래밍 놀이터/안드로이드, Java

[Android/안드로이드] Service 에 대해 알아본다.

by 돼지왕 왕돼지 2012. 2. 18.
반응형


안녕하세요 돼지왕 왕돼지입니다.
오늘은 안드로이드 4대 컴포넌트 중 하나인 서비스 ( Service ) 에 대해 전반적인 내용을 알아보도록 하겠습니다.

 

서비스에 대한 간략한 소개


 - 서비스는 백그라운드 데몬 이라고 볼 수 있는데, 백그라운드에서 계속 실행되는 프로세스를 말합니다.
 - 서비스 관련하여 원격 호출 인터페이스( AIDL )라는 녀석이 있는데, 자신의 기능을 메서드로 노출하고 클라이언트가 메서드를 호출해서 서비스 이용하는 형태를 말합니다.
 
2012/02/15 - [프로그래밍 놀이터/안드로이드] - [Android/안드로이드] Service 생명주기.
 

2012/02/08 - [프로그래밍 놀이터/안드로이드] - [android/안드로이드] aidl 을 이용하여 service 에 bind 하기.
 


Service sample code

 
<service 정의>

public class NewsService extends Service{
   boolean mQuit;
 
   public void onCreate(){}
   public void onDestory(){
      super.onDestory();
      mQuit = true;
   }
  
   publid int onStartCommand (Intent intent, int flags, int startId){
      super.onStartCommand(intent, flags, startId);
      mQuit = false;
      NewsThread thread = new NewsThread(this, mHandler);
      thread.start();
      return START_STICKY:
   }
 
   public IBinder onBind (Intent intent){
      return null;
   }
 
   class NewsThread extends Thread{
      NewsService mParent;;
      Handler mHandler;
      String[] arNews = {"abc", "bbc", "ccc" ...};
 
      public NewsThread(NewsService parent, Handler handler){
         mParnet = parent;
         mHandler = handler;
      }
 
      public void run(){
         for (int idx = 0; mQuit == false; idx++){
            Message msg =new Message();
            msg.what = 0;
            msg.obj = arNews[idx % arNews.length];
            mHandler.sendMessage(msg);
            try {Thread.sleep(5000);} catch (Exception e){;}
         }
      }
   }
 
   Handler mHandler = new Handler(){
      public void handleMessage(Message msg){
         if (msg.what == 0){
            // To do
         }
      }
   }
}



<service 실행>

Intent intent = new Intent(.this, NewsService.class);
startService(intent);



<service 정지>

Intent intent = new Intent(.this, NewsService.class);
stopService(intent);


 
 

Service Manifest 등록


서비스도 응용 프로그램을 구성하는 컴포넌트이므로 매니페스트에 등록해야만 사용 가능합니다.

<service android:name=".NewsService" android:enabled = "true">
   <intent-filter>
      <action android:name="exam.service.NEWS"/>
   </intent-filter>
</service>

 

로그인 없이 추천 가능합니다. 손가락 꾸욱~

반응형

댓글