서비스란 안드로이드의 대표 컴포넌트 중 하나로 백그라운드에서 필요한 작업시 사용할 수 있는 컴포넌트를 이야기 함.

 

 

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();
                Log.d(TAG, "onClick: "+name);

                Intent intent = new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("command","show");
                intent.putExtra("name",name);
                startService(intent);
            }
        });

 서비스를 실행 할 때는 startService 메소드를 사용한다.

 

 

-Service.java-

public class MyService extends Service {
    private static final String TAG = "MainMyService";

    public MyService() {
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {  //flags: 잘 실행되고 있는지 코드값 리턴
        Log.d(TAG, "onStartCommand: 호출됨 "+flags+", "+startId);

        if(intent ==null){
            return Service.START_STICKY;    //다시 리스타트
        }else{
            processCommand(intent);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void processCommand(Intent intent) {
        String command = intent.getStringExtra("command");
        String name = intent.getStringExtra("name");

        Log.d(TAG, "processCommand: "+command+", "+name);

        for(int i=0;i<5;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "Waiting :"+ i+" second...");
        }
    }

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

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

 서비스 엑티비티가 호출되면 onCreate() ->onstartCommand() 순으로 실행이 된다

메인에서 넘어온 INTENT가 널 값이 아니면 processCommand() 메소드가 실행이 되고 백그라운드 상태에서 동작이 되도록 한다. 

 

-Main.java-

 button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),MyService.class);
                stopService(intent);
            }
        });

메인 엑티비티에서  서비스 종료를 시키려면 stopService메소드를 사용하여 종료를 시킨다.

 

종료 버튼을 누르면

 

-Service.java-

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

서비스가 종료되어 onDestory()가 호출되어 종료되어진다.

더보기

-Main.java-

package com.example.my13_service;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    EditText editText;
    Button button1,button2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText=findViewById(R.id.editText);
        button1=findViewById(R.id.button1);
        button2=findViewById(R.id.button2);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editText.getText().toString();
                Log.d(TAG, "onClick: "+name);

                Intent intent = new Intent(getApplicationContext(),MyService.class);
                intent.putExtra("command","show");
                intent.putExtra("name",name);
                startService(intent);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),MyService.class);
                stopService(intent);
            }
        });
    }
}

 

-service.java-

package com.example.my13_service;

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

public class MyService extends Service {
    private static final String TAG = "MainMyService";

    public MyService() {
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {  //flags: 잘 실행되고 있는지 코드값 리턴
        Log.d(TAG, "onStartCommand: 호출됨 "+flags+", "+startId);

        if(intent ==null){
            return Service.START_STICKY;    //다시 리스타트
        }else{
            processCommand(intent);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void processCommand(Intent intent) {
        String command = intent.getStringExtra("command");
        String name = intent.getStringExtra("name");

        Log.d(TAG, "processCommand: "+command+", "+name);

        for(int i=0;i<5;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "Waiting :"+ i+" second...");
        }
    }

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

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

'For developer > Android' 카테고리의 다른 글

(Android)my15_touchevent  (0) 2020.05.27
(Android)my14_smsservice  (0) 2020.05.27
(Android)my11_dialog_대화상자  (0) 2020.05.21
(Android)my10_intentresult  (0) 2020.05.21
(my09_layoutinflate)인플레이트  (0) 2020.05.21

+ Recent posts