안드로이드

 

 

 

 

 

 

 

 

 

 

 

 

//액티비티 :화면 처리 클래스
//리시버 :화면 없음, 수신적용
//서비스 : 화면 없음, 백그라운드 작업용
class ServiceActivity
package com.example.choi.ex10_service;

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

//액티비티 :화면 처리 클래스
//리시버 :화면 없음, 수신적용
//서비스 : 화면 없음, 백그라운드 작업용

public class ServiceActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.service);
    }


    public void onClick(View v){
        Intent intent = new Intent(this, MyService.class);
        switch (v.getId()){
            case R.id.button1:
                startService(intent); //서비스 시작 요청
                break;
            case R.id.button2:
                stopService(intent); //서비스 종료 요청
                // => onDestroy() 호출
                break;
        }

    }


}

 

 

service.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/service"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.choi.ex10_service.ServiceActivity">

    <Button
        android:text="서비스 시작"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:id="@+id/button1"
        android:onClick="onClick"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="서비스 멈춤"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignStart="@+id/button1"
        android:layout_marginTop="46dp"
        android:onClick="onClick"
        android:id="@+id/button2" />



</RelativeLayout>

 

 

class MyService
package com.example.choi.ex10_service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

// 1.서비스 : 단순 백그라운드 작업
// 2. 바인딩  서비스 (서비스에 요청 => 서비스에서 응답)


public class MyService extends Service {
    //서비스 종료를 위한 변수
    boolean isQuit;

    public MyService() {

    }


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

    //startSerivce()
    //서비스가 생성될 때 (최초 1회)
    @Override
    public void onCreate() {
        super.onCreate();
    }


    //서비스 시작
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
       //상태변수를 진행중으로 변경
        isQuit =false;
        //백그라운드 스레드 시작
        MyThread th =new MyThread(this);
        th.start();
        //서비스가 강제로 종료될 경우 null 을 리턴하는 옵션
        return Service.START_STICKY;
        //아무동작을 하지 않음
        //return Service.START_NOT_STICKY;
        //서비스를 재시작 시킴
        //return Service.START_REDELIVER_INTENT;
    }


    // stopService()
// 서비스 멈출 때
    @Override
    public void onDestroy() {
        super.onDestroy();
        isQuit=true;
        Toast.makeText(getApplicationContext(), "종료되었습니다.", Toast.LENGTH_LONG).show();
    }

    //핸들러
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //핸들러에 전달된 메시지를 처리하는 method
            if(msg.what==0){ //What 값이 0이면
                String item =(String)msg.obj; //실제 전송값
                //getApplicationContext() 토스트를 출력할 화면
                Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
                return true;
            }

            return false;
        }
    });



    //내부 클래스
    class MyThread extends Thread{

        String[] items={"사과", "포도", "바나나", "살구", "레몬"};

        public MyThread(MyService parent) {

        }

        @Override
        public void run() {
            for(int i=0; isQuit==false; i++){
                //핸들러에 전송할 메시지 객체
                Message msg=new Message();
                msg.what=0; //메시지의 식별자
                msg.obj=items[i %items.length];
                //핸들러에게 메시지 전달
                handler.sendMessage(msg);
                try {
                    Thread.sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    }








}


 

 

 

 

about author

PHRASE

Level 60  머나먼나라

먹기는 혼자 먹어도 일은 혼자 못 한다 , 일은 협동해서 하는 편이 효과적이라는 말.

댓글 ( 4)

댓글 남기기

작성