안드로이드 프로그래밍[JAVA Code]/Service

Service : 서비스

훈츠 2019. 12. 2. 03:13
반응형

서비스는 백그라운드에서 실행 되어 사용자와 상호 작용할 필요 없이 장시간 실행 되는 작업을 수행하는 구성 요소 이다. 응용 프로그램이 손상된 경우에도 작동한다. 서비스는 두가지 상태를 취 할수 있다. 

1) startService() 호출하여 서비스를 시작할 때 서비스가 시작된다. 시작된 서비스는 시작된 구성요소가 손상되더라도 백그라운드에서 무기한으로 실행 될수 있다.

2) bindService()를 호출하여 응용 프로그램 구성 요소가 바인딩 될때 서비스가 바인딩 된다. 바인딩 된 서비스는 구성 요소가 서비스와 상호 작용하고, 요청을 보내고, 결과를 얻거나, 프로세스 간 통신 (IPC)을 통해 프로세스간에 수행 할 후있는 클라이언트-서버 인터페이스를 제공 한다.

서비스에는 서비스 상태의 변경 사항을 모니터링하기 위해 구현할 수있는 수명주기 콜백 메소드가 있으며 적절한 단계에서 작업을 수행 할 수 있다. 왼쪽의 다음 다이어그램은 서비스가 startService ()로 작성 될 때의 수명주기를 표시하고 오른쪽의 다이어그램은 서비스가 bindService ()로 작성 될 때의 수명주기를 표시한다. 

서비스 생명 주기 

서비스를 작성하려면 서비스 기본 클래스 또는 기존 서브 클래스 중 하나를 확장하는 Java 클래스를 작성 해야한다. 서비스 기본 클래스는 다양한 콜백 메소드를 정의하며 가장 중요한 것은 각각을 이해하고 앱이 사용자가 원하는 방식으로 동작하도록 하는것을 구현 하는것 이다. 그러므로 모든 콜백 메소드를 구현할 필요는 없다. 

Sr.No.Callback & Description

1

onStartCommand()

액티비티 같은 다른 구성요소가 startService()를 호출 하는 경우 시스템은 이 메소드를 호출한다. 이럴경우 반드시 user가 stopService() 메소드 혹은 stopSelf로 서비스를 중지 해야한다.  

2

onBind()

시스템은 다른 구성 요소가 bindService ()를 호출하여 서비스와 바인드하려고 할 때이 메소드를 호출한다. 이 메소드를 구현하는 경우 IBinder 오브젝트를 리턴하여 클라이언트가 서비스와 통신하는 데 사용하는 인터페이스를 제공해야한다. 항상이 메서드를 구현해야하지만 바인딩을 허용하지 않으려면 null을 반환 하면 된다.

3

onUnbind()

모든 클라이언트가 서비스에 의해 게시 된 특정 인터페이스와의 연결이 끊어지면 시스템은이 메소드를 호출한다.

4

onRebind()

이전에 모든 클라이언트가 onUnbind (Intent)에서 연결이 끊어 졌다는 알림을받은 후 새 클라이언트가 서비스에 연결되면 시스템은이 메소드를 호출한다.

5

onCreate()

시스템은 서비스가 onStartCommand () 또는 onBind ()를 사용하여 처음 작성 될 때 이 메소드를 호출한다. 이 설정은 일회성 설정을 수행하는 데 필요하다.

6

onDestroy()

서비스가 더 이상 사용되지 않고 파괴 될 때 시스템은이 메소드를 호출한다. 서비스는 스레드, 등록 된 리스너, 수신자 등과 같은 자원을 정리하기 위해이를 구현해야 한다.

1. MainActivity 에서 Service 시작과 종료 하는 예시 

package com.example.tutorialspoint7.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {
   String msg = "Android : ";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.d(msg, "The onCreate() event");
   }

   public void startService(View view) {
      startService(new Intent(getBaseContext(), MyService.class));
   }

   // Method to stop the service
   public void stopService(View view) {
      stopService(new Intent(getBaseContext(), MyService.class));
   }
}

2. 서비스 예시 : onstartCommand() and onDestory() 메소드

package com.example.tutorialspoint7.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
   * Created by TutorialsPoint7 on 8/23/2016.
*/

public class MyService extends Service {
   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }
	
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

 3. Manifest 에 등록 : Sms 받는 name = "android.intent.Telephony_SMS_RECEIVED"

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint7.myapplication">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
		
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
		
      <service android:name=".MyService" />
   </application>

</manifest>

 

반응형