투케이2K

127. (AndroidStudio/android/java) 서비스 (Service) 사용해 백그라운드 상태에서 주기적 반복 작업 수행 본문

Android

127. (AndroidStudio/android/java) 서비스 (Service) 사용해 백그라운드 상태에서 주기적 반복 작업 수행

투케이2K 2021. 5. 2. 11:41
반응형

/* =========================== */

[ 개발 환경 설정 ]

개발 툴 : AndroidStudio

개발 언어 : java

/* =========================== */

/* =========================== */

[소스 코드]

[AndroidManifest.xml 파일]

<액티비티 등록 부분>
<activity
            android:name=".A_BackgroundService"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan"/>



<서비스 등록 부분>
<service
            android:name=".A_BackgroundServiceReceiver"
            android:enabled="true"
            android:exported="true"
            android:stopWithTask="false" />

[JAVA 파일 : A_BackgroundService]

        //================================ [버튼 클릭 이벤트] =======================================
        start_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Toast.makeText(getApplication(), "서비스를 시작합니다 ... ",Toast.LENGTH_SHORT).show();
                    setServiceStart();
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        //================================ [버튼 클릭 이벤트] =======================================
        stop_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Toast.makeText(getApplication(), "서비스를 종료합니다 ... ",Toast.LENGTH_SHORT).show();
                    setServiceStop();
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

[JAVA 파일 : A_BackgroundServiceReceiver]

    //TODO [실시간 핸들러 작업 시작 명령]
    public void getHandlerStart(){
        Log.d("---","---");
        Log.d("//===========//","================================================");
        Log.d("","\n"+"[A_BackgroundServiceReceiver > getHandlerStart() 메소드 : 실시간 작업 시작]");
        Log.d("//===========//","================================================");
        Log.d("---","---");
        try {
            mHandler.sendEmptyMessage(0);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    //TODO [실시간 핸들러 작업 종료 명령]
    public void getHandlerStop(){
        Log.d("---","---");
        Log.d("//===========//","================================================");
        Log.d("","\n"+"[A_BackgroundServiceReceiver > getHandlerStop() 메소드 : 실시간 작업 종료]");
        Log.d("//===========//","================================================");
        Log.d("---","---");
        try {
            mHandler.removeMessages(0);
            //mHandler.removeCallbacks(null);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    //TODO [실시간 핸들러 작업 처리 부분]
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("---","---");
            Log.w("//===========//","================================================");
            Log.d("","\n"+"[A_BackgroundServiceReceiver > Handler 메소드 : 실시간 작업 ["+String.valueOf(getNowDateTime24())+"]"+" ]");
            Log.w("//===========//","================================================");
            Log.d("---","---");
            //TODO [작업 내용 작성 부분]
            try {
                Toast.makeText(getApplicationContext(),String.valueOf(getNowDateTime24()),Toast.LENGTH_SHORT).show();
            }
            catch (Exception e){
                e.printStackTrace();
            }

            //TODO [자기 자신을 1초마다 호출(무한 루프로 호출)]
            try {
                mHandler.sendEmptyMessageDelayed(0, 5000);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };

[XML 파일 : activity_a_background_service.xml]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:id="@+id/parent">
    <!--    [editText 사용시 자동으로 포커스활성 방지]-->
    <!--    android:focusable="true"-->
    <!--    android:focusableInTouchMode="true"-->
    <!--    android:id="@+id/parent"-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- ====== [타이틀 레이아웃] ====== -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:orientation="horizontal"
            android:background="#343d46"
            android:layout_marginBottom="10dp">
            <TextView
                android:id="@+id/title_text"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="[ 백그라운드 서비스 ]"
                android:textColor="#ffffff"
                android:textSize="23dp"
                android:textStyle="bold"
                android:gravity="center"/>
        </LinearLayout>

        <!-- ====== [카드 레이아웃] ====== -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="#343d46"
            android:layout_margin="15dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="6.5"
                android:orientation="horizontal"
                android:layout_marginTop="20dp"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="0dp">
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:src="@drawable/url_icon"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:layout_marginTop="15dp"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="20dp">

                <Button
                    android:id="@+id/start_button"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="서비스 시작"
                    android:textStyle="bold"
                    android:textSize="13dp"
                    android:gravity="center"
                    android:textColor="#000000"
                    android:background="@drawable/white_button_bg"
                    android:layout_marginTop="0dp"
                    android:layout_marginLeft="0dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginBottom="0dp" />

                <Button
                    android:id="@+id/stop_button"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="서비스 종료"
                    android:textStyle="bold"
                    android:textSize="13dp"
                    android:gravity="center"
                    android:textColor="#000000"
                    android:background="@drawable/white_button_bg"
                    android:layout_marginTop="0dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginRight="0dp"
                    android:layout_marginBottom="0dp" />

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>
​

/* =========================== */

/* =========================== */

[결과 출력]

/* =========================== */

/* =========================== */

[첨부 파일 - 전체 소스코드]

 

소스코드.txt
0.02MB

/* =========================== */

반응형
Comments