오래된글/Articles

Android Service Component(Start/Stop type)

Records that rule memory 2018. 4. 19. 14:30
728x90

Introduction

사용자 Interface 환경 필요 없이 긴 시간 동안 작업이 Background 상태로 실행되는 Application 컴포넌트를 “Service”라 합니다.


Service Component에는 2가지 Type이 있습니다.


  1. Started: 이 타입은 다른 어플리케이션 컴포넌트에 의해서 시작(Started)되는 Service입니다. 한번 시작되면 종료 시켜주기 전까지 계속하여 실행됩니다.

  2. Bound: 다른 어플리케이션 컴포넌트의 “bindService” Method가 실행될 때 함께 실행되는 형태입니다. Client-Server 커뮤니케이션에 유용하게 사용됩니다. 또한 서로 다른 프로세스 사이에서도 수행할 수 있고 여러 호출자들이 Service에 바인딩 할 수 있습니다.  서비스에 바인된 호출자가 최소한 하나라도 있을 때까지만 활성화 됩니다.


본 문서에서는 Started Type의 Service에 관해서 살펴보도록 하겠습니다.


Step 1: Service Component 생성


import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.widget.Toast;


/**

*

* @author openmobster@gmail.com

*/

public class DemoService extends Service


Step 2: onStartCommand callback 메서드 구현


@Override

public int onStartCommand(Intent intent, int flags, int startId)

{

       super.onStartCommand(intent, flags, startId);

       

       //Announcement about starting

       Toast.makeText(this, "Starting the Demo Service", Toast.LENGTH_SHORT).show();

       

       //Start a Background thread

       isRunning = true;

       Thread backgroundThread = new Thread(new BackgroundThread());

       backgroundThread.start();

       

   // We want this service to continue running until it is explicitly

   // stopped, so return sticky.

   return START_STICKY;

}


Step 3: onDestory callback 메서드 구현


@Override

public void onDestroy()

{

       super.onDestroy();

       

       //Stop the Background thread

       isRunning = false;

       

       //Announcement about stopping

       Toast.makeText(this, "Stopping the Demo Service", Toast.LENGTH_SHORT).show();

}


Step 4: Background Thread 구현


private class BackgroundThread implements Runnable

{

       int counter = 0;

       public void run()

       {

               try

               {

                       counter = 0;

                       while(isRunning)

                       {

                               System.out.println(""+counter++);

                               Thread.currentThread().sleep(5000);

                       }

                       

                       System.out.println("Background Thread is finished.........");

               }

               catch(Exception e)

               {

                       e.printStackTrace();

               }

       }

}


Step 5: “AndroidManifest.xml”에 Service 등록


<service android:name="org.openmobster.app.DemoService">

       <intent-filter>

               <action android:name="org.openmobster.app.DemoService"/>

       </intent-filter>

</service>


Step 6: Activity에서 Service 실행


//Start the Service

Intent start = new Intent("org.openmobster.app.DemoService");

MainActivity.this.startService(start);


Step 7: Service 종료


Intent stop = new Intent("org.openmobster.app.DemoService");

MainActivity.this.stopService(stop);


728x90