https://blog.devgenius.io/how-to-use-biometric-authentication-in-kotlin-9885f372230f

 

How to use Biometric Authentication in Kotlin

You can use biometric authentication, like face recognition or fingerprint recognition, to protect sensitive data or premium content in…

blog.devgenius.io

오늘도 한걸음 배워 보도록 하겠다.  다른 게 아니라 로그인할 때 지문을 이용하여 로그인하는 기능을 구현해 보는 케이스를 찾았다. 그것도 kotlin으로 말이다. 

 

다음 앱을 개발할 때 적용해 보아야겠다. 그래서 오늘도 레이하네 에 자파나 님에게 허락을 득하지는 않았지만, 그분이 작성해 놓은 source을 읽어 보면서 배워 보도록 하겠다. 

 

먼저 gradle에 설정을 해야 한다. 

 

implementation "androidx.biometric:biometric-ktx:1.2.0-alpha04"

현재까지는 저버 전이 최종인 것 같다. 저것을 이용하면 지문 인증이 수월하게 구현이 되는 걸 배웠다.

 

화면구현

작성자님이 만들어 놓은 화면은 지문 이미지 하나, 

동작을 실행할 버튼 하나,  상태를 표현할 text 하나

 

3개가 들어 있는 화면을 구성했다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

다음은 아래처럼 지문 동작을 사용할 수 있는지 체크하는 함수를 기술한다.  지문 인식 기능을 구동해 보아야 하기 때문에 AVD에서는 설정에 따라 동작에 오류가 발생할 수 도 있다. 그래서 실물 폰에서 디버깅을 해 보는 것이 좋을 것 같다.

fun checkDeviceHasBiometric() {
    val biometricManager = BiometricManager.from(this)
    when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)) {
        BiometricManager.BIOMETRIC_SUCCESS -> {
            Log.e("MY_APP_TAG", "App can authenticate using biometrics.")
            info = "App can authenticate using biometrics."
            binding.btnLogin.isEnabled = true

        }
        BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
            Log.e("MY_APP_TAG", "No biometric features available on this device.")
            info = "No biometric features available on this device."
            binding.btnLogin.isEnabled = false

        }
        BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> {
            Log.e("MY_APP_TAG", "Biometric features are currently unavailable.")
            info = "Biometric features are currently unavailable."
            binding.btnLogin.isEnabled = false

        }
        BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
            // Prompts the user to create credentials that your app accepts.
            val enrollIntent = Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
                putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
                    BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
            }
            binding.btnLogin.isEnabled = false

            startActivityIfNeeded(enrollIntent, 100)
        }
    }
    binding.tvMsg.text = info
}

상태를 확인하고 동작이 가능하다고 하면 이번에는 main activity에서 동작을 실행할 부분을 구현해 보는 것이다. 

 

private lateinit var executor: Executor
private lateinit var biometricPrompt: BiometricPrompt
private lateinit var promptInfo: BiometricPrompt.PromptInfo

선언된 변수를 보면 Excutor 실행자라고 봐야 하는 건가? 아직 잘 이해가 되지 않는 것이 하나 있고, 지문인식 안내 창에 사용할 프롬프트 선언과, 프롬프트 정보가 들어가는 것 하나 이렇게 선언이 되어 있다.

 

executor = ContextCompat.getMainExecutor(this)
biometricPrompt = BiometricPrompt(this, executor,
    object : BiometricPrompt.AuthenticationCallback() {
        override fun onAuthenticationError(
            errorCode: Int,
            errString: CharSequence,
        ) {
            super.onAuthenticationError(errorCode, errString)
            Toast.makeText(applicationContext,
                "Authentication error: $errString", Toast.LENGTH_SHORT)
                .show()
        }

        override fun onAuthenticationSucceeded(
            result: BiometricPrompt.AuthenticationResult,
        ) {
            super.onAuthenticationSucceeded(result)
            Toast.makeText(applicationContext,
                "Authentication succeeded!", Toast.LENGTH_SHORT)
                .show()
        }

        override fun onAuthenticationFailed() {
            super.onAuthenticationFailed()
            Toast.makeText(applicationContext, "Authentication failed",
                Toast.LENGTH_SHORT)
                .show()
        }
    })

promptInfo = BiometricPrompt.PromptInfo.Builder()
    .setTitle("Biometric login for my app")
    .setSubtitle("Log in using your biometric credential")
    .setNegativeButtonText("Use account password")
    .build()

// Prompt appears when user clicks "Log in".
// Consider integrating with the keystore to unlock cryptographic operations,
// if needed by your app.

binding.btnLogin.setOnClickListener {
    biometricPrompt.authenticate(promptInfo)
}

핵심은 이렇게 구현된 것인데, 필요에 따라 수정해 사용하면 될 것 같다.

excutor는 실행자가 이 앱이라는 것을 선언한다고 이해가 될 것 같기는 하다.

다음은 biometric prompt를 실행해서 지문 인식을 구동하고 결과를 받아서 다음 처리를 구현하면 될 것 같다. 

그다음은 promptInfo을 설정해서 지문인식 창이 구동되었을 때 나오는 안내문구 등을 선언할 수 있고, setNegativeButtonText을 이용해서 지문인식이 아닌 다른 방식으로 전환을 유도하는 안내문구도 달아볼 수 있을 것 같다.

 

이제 구동을 시켜 보는 것으로 끝.

 

구동화면

한 가지 또 보이지 않았던 것은 지문인증 이 실행된 상태에서는 화면 캡처가 되지 않는 다. 이건 보너스(?) 인가? 그래서 노트북 카메라로 찍었다.

 

나도 배우는 중이니, 전체 소스는 원작자의 글에서 찾아보시는 것으로 다가... git에 전체 소스가 있으니 배우는 데는 그렇게 어렵지 않을 것으로 생각된다.   다시 한번 원작자 님에게 감사를 드리며... 저 글을 읽고 나서 박수를 한번 쳐 드렸다.

 

반응형

https://yunaaaas.tistory.com/19

 

[Android/Kotlin] 언어설정 (Eng / Kor) 변경하기

2020 스마트 관광 앱 개발 공모전에 K-Pop 명소 추천 플랫폼인 'Kravel'을 개발하였는데요. 외국인을 타겟으로 한 앱이다 보니 영어/중국어,등 설정언어를 변경할 수 있도록 해주는 기능 이 필요했습

yunaaaas.tistory.com

먼저 이글은 위 게시물에 기반해서 작성된 것임을 밝힘.

 

앱을 만들면서 여러나라 사람이 사용할 수 있는 앱을 만들고 싶다. 그래서 번역 API 을 활용하는 앱을 만들기 시작했다. 그러다 보니, 나의 앱은 우리나라에서만 사용하는 사람들을 위한 앱이 되어 가고 있는데, 이 나라에 온 사람들이 다 자기 나라말을 하고 싶을 것이다. 

 

 

그래서 앱의 언어 설정을 변경하는 기능을 구현해 보기록 했다.  코드 구현은 다음과 같이 했다.

 

private fun setLocale(Lang: String) {
    Log.e("로그", "setLocale=$Lang" )
    val locale = Locale(Lang) // Local 객체 생성. 인자로는 해당 언어의 축약어가 들어가게 됩니다. (ex. ko, en)
    Locale.setDefault(locale) // 생성한 Locale로 설정을 해줍니다.

    val config = Configuration() //이 클래스는 응용 프로그램이 검색하는 리소스에 영향을 줄 수 있는
    // 모든 장치 구성 정보를 설명합니다.

    config.setLocale(locale) // 현재 유저가 선호하는 언어를 환경 설정으로 맞춰 줍니다.
    baseContext.resources.updateConfiguration(config, baseContext.resources.displayMetrics)

    val intent = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
    intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
    intent!!.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    finish()
    startActivity(intent)
}

다만, 한국어 설정시 ko 로 해야 하는 동작을 한다는 것, kr 이라고 생각을 할 수 도 있지만...  이제 다른 나라 언어도 설정을 해 보아야겠다.   다국어 버전을 만들기 위해서는  잘 하지 못하는 영어이기는 하지만, default 을 영어로 설정하는 것이 도움이 된다.   위 예시와 같이 locale 설정을 변경한 다음 화면을 다시 그려야 하기 때문에 강제로 앱을 종료하고 새로 실행하는 방식으로 해결을 한 원작자의 의도(?)을 이해 할 수 있었다.

 

언어변환예시

 

그 다음은 아래 포스팅을 참고 해서 이런 저런 나라의 언어로 번역된 파일을 만들어 보는 것이다. 그리고 나서

그것을 내 프로젝트의 res 폴더 아래  values-ko-rKr (한국어) 부터 폴더별로 string.xml 파일을 만들어 담아 보자.

 

https://billcorea.tistory.com/37

 

안드로이드 다국적(?) 앱 만들어 보기 (feat 카카오 번역 API, python 활용)

앱을 만들어 등록하는 동안 하고 싶은 것 중에서 한가지는 여러나라의 언어로 배포를 해 보는 것이였다. 예전에는 그걸 하나 하나 번역을 해 가면서 등록을 했던 것을 카카오 번역 API 호출하여

billcorea.tistory.com

 

마무리가 다 되면 다시 이글을 업데이트 하도록 해야겠다.

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

반응형

https://itnext.io/a-comprehensive-guide-to-android-12s-splash-screen-api-644609c811fa

 

A Comprehensive Guide to Android 12’s Splash Screen API

For years Android Devs have always resorted to using a windowBackground or Activity or Fragment for their splash screen. Using the…

itnext.io


스플래쉬 화면 : 앱이 실행 되기 전에 로딩중 보이는 화면 ( 앱이 처리 되는 동안 보이는 progressbar 와는 다른 ...)

오늘은 인터넷에서 퍼온 글 하나를 올려 본다.

요새 배우는중인 jetpack compose 통해서 화면 작업을 해 보고 있는데, splash 화면 만드는 가이드가 나와 있어서 퍼 왔다.

시간이 생기면 작업중인 앱에 적용을 해 보아야 겠다.


반응형

Compose을 활용한 앱을 구현하는 동안에 이전에 만들었던 layout 을 활용하고자 하는 경우가 생긴다면... Androind ViewBinding을 활용하는 방법이 있었다.

 

https://developer.android.com/jetpack/compose/interop/interop-apis?hl=ko 

 

상호 운용성 API  |  Jetpack Compose  |  Android Developers

상호 운용성 API 앱에 Compose를 채택하는 동안 Compose와 뷰 기반 UI를 결합할 수 있습니다. 다음에는 Compose로의 전환을 보다 쉽게 할 수 있는 API, 권장사항 및 팁이 나와 있습니다. Android 뷰의 Compose

developer.android.com

 

 

구현을 시작해 보면, 먼저 gradle 파일에 implementation 을 추가해야 한다. 

implementation "androidx.compose.ui:ui-viewbinding:$compose_version"

 다음은 채팅방 구현을 위해서 예전에 만들었던 코드에서 Recycleview 을 활용했던 layout을 가지고 왔다.

 

layout 예제

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".ChatRoomActivity">

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="vertical"
        android:weightSum="5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="5"
            android:orientation="horizontal"
            android:weightSum="10">

            <TextView
                android:id="@+id/textView11"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="2"
                android:gravity="center_horizontal|center_vertical"
                android:text="현재시간" />

            <TextClock
                android:id="@+id/textView10"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="7"
                android:format12Hour="hh:mm"
                android:format24Hour="HH:mm"
                android:gravity="center_horizontal|center_vertical" />

        </LinearLayout>

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:name="com.roopre.simpleboard.Fragment.ChatMsgFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layoutManager="LinearLayoutManager"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2"
        tools:context=".Fragment.ChatMsgFragment"
        tools:listitem="@layout/custom_chat_msg" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <EditText
            android:id="@+id/content_et"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/bg_content_et"
            android:hint="메시지를 입력하세요."
            android:lines="1"
            android:maxLines="1"
            android:padding="8dp" />

        <ImageView
            android:id="@+id/send_iv"
            android:layout_width="40dp"
            android:padding="2dp"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_send" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

다음은 recycleview 에 들어갈 item layout은 다음과 같이 구현하였다. 

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/other_cl"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/my_cl"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/userid_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:text="userid_tv"
            android:textSize="16sp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/date_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="date_tv"
            android:textSize="10sp"
            app:layout_constraintStart_toStartOf="@+id/userid_tv"
            app:layout_constraintTop_toBottomOf="@+id/userid_tv" />

        <TextView
            android:id="@+id/content_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@drawable/bg_content_et"
            android:padding="8dp"
            android:text="content_tv"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="@+id/date_tv"
            app:layout_constraintTop_toBottomOf="@+id/date_tv" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/my_cl"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/other_cl">

        <TextView
            android:id="@+id/userid_tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="16dp"
            android:text="userid_tv"
            android:textSize="16sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/date_tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:layout_marginEnd="16dp"
            android:text="date_tv2"
            android:textSize="10sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/userid_tv2" />

        <TextView
            android:id="@+id/content_tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="16dp"
            android:background="@drawable/bg_content_et"
            android:padding="8dp"
            android:text="content_tv2"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/date_tv2"
            app:layout_constraintVertical_bias="0.0" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 

그리고 Recycleview 에 데이터를 넣고 구현하기 위해서 adapter을 구현하였다. 

 

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.compose.runtime.snapshots.SnapshotStateList;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.billcoreatech.multichat416.R;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {

    private static final String TAG = "ChatAdapter";
    private final ArrayList<ChatMessage> chatMsgModels;
    String displayName ;

    public ChatAdapter( ArrayList<ChatMessage> items, String displayName) {
        this.chatMsgModels = items;
        this.displayName = displayName;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.custom_chat_msg, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        ChatMessage vo = chatMsgModels.get(position);
        try {
            Log.e(TAG, " userId=" + vo.getDisplayName()+ ": displayName=" + displayName) ;

        } catch (Exception e) {

        }
        if (vo.getDisplayName().equals(displayName)) {
            holder.other_cl.setVisibility(View.GONE);
            holder.my_cl.setVisibility(View.VISIBLE);

            holder.userid_tv2.setText(vo.getDisplayName());
            holder.date_tv2.setText(vo.getCrtDtim());
            holder.content_tv2.setText(vo.getContent());
        }else
        {
            holder.other_cl.setVisibility(View.VISIBLE);
            holder.my_cl.setVisibility(View.GONE);

            holder.userid_tv.setText(vo.getDisplayName()); // userId 대신 nickName 으로 대체
            holder.date_tv.setText(vo.getCrtDtim());
            holder.content_tv.setText(vo.getContent());
        }
    }

    @Override
    public int getItemCount() {
        return chatMsgModels.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ConstraintLayout my_cl, other_cl;
        public TextView userid_tv, date_tv, content_tv, userid_tv2, date_tv2, content_tv2;

        public ViewHolder(View view) {
            super(view);
            my_cl = view.findViewById(R.id.my_cl);
            other_cl = view.findViewById(R.id.other_cl);
            userid_tv = view.findViewById(R.id.userid_tv);
            date_tv = view.findViewById(R.id.date_tv);
            content_tv = view.findViewById(R.id.content_tv);
            userid_tv2 = view.findViewById(R.id.userid_tv2);
            date_tv2 = view.findViewById(R.id.date_tv2);
            content_tv2 = view.findViewById(R.id.content_tv2);

            // 2021.11.01 item 클릭 처리를 위해서 추가
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    int pos = getAdapterPosition() ;
                    if (pos != RecyclerView.NO_POSITION) {
                        // 리스너 객체의 메서드 호출.
                        if (mListener != null) {
                            mListener.onItemClick(v, pos) ;
                        }
                    }
                }
            });
        }
    }

    // 2021.11.01 리스너 객체 참조를 저장하는 변수
    private OnItemClickListener mListener = null ;

    // OnItemClickListener 리스너 객체 참조를 어댑터에 전달하는 메서드
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mListener = listener ;
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int position) ;
    }
}

 

다음은 데이터를 넣기 위한 구조체는 다음 처럼 구현을 하였다.

 


data class ChatMessage(
    var displayName:String = "",
    var crtDtim:String = "",
    var content:String = ""
)

kotlin 으로 구현을 하면서 좋은 것은 source code 가 간소화된다는 것이다. java로 구현했다면 getter / setter을 다 넣어 주었어야 하겠지만, kotlin 으로 구현하다 보니 그럼 군더더기는 필요가 없게 되었다.

 

이번에는 채팅방 운영을 위한 activity code을 구현해 보았다.

 

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.KeyEvent.KEYCODE_ENTER
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.Logout
import androidx.compose.material.icons.filled.ManageAccounts
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidViewBinding
import androidx.core.content.ContextCompat
import com.billcoreatech.multichat416.databean.ChatAdapter
import com.billcoreatech.multichat416.databean.ChatMessage
import com.billcoreatech.multichat416.databean.ChatMessageViewModel
import com.billcoreatech.multichat416.databinding.ActivityChatRoomBinding
import com.billcoreatech.multichat416.ui.theme.MultiChat416Theme
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class ChatRoomActivity : ComponentActivity() {

    var TAG = "ChatRoomActivity"

    lateinit var displayName:String
    lateinit var auth: FirebaseAuth
    lateinit var sp: SharedPreferences
    lateinit var sdf:SimpleDateFormat
    private val database = Firebase.database
    private val chatMessages = database.getReference("ChatMessage")
    lateinit var df:SimpleDateFormat
    lateinit var chatId:String
    lateinit var startDt:String
    lateinit var adapter:ChatAdapter
    var chatMesgItems = ArrayList<ChatMessage>()
        private set
    lateinit var binding:ActivityChatRoomBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        auth = Firebase.auth
        sp = getSharedPreferences("MultiChat", MODE_PRIVATE)
        sdf = SimpleDateFormat("yyyyMMddHHmmss")
        df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        chatId = intent.getStringExtra("chatId") as String
        startDt = intent.getSerializableExtra("startDt") as String
        Log.e(TAG, "${startDt}")
        displayName = auth.currentUser?.displayName.toString()

        chatMesgItems.clear()
        adapter = ChatAdapter(chatMesgItems, displayName)
        binding = ActivityChatRoomBinding.inflate(layoutInflater)

        setContent {
            val isDarkTheme = remember { mutableStateOf(false) }
            if(isDarkTheme.value){
                this.window.statusBarColor = ContextCompat.getColor(this, R.color.softBlack)
            }else{
                this.window.statusBarColor = ContextCompat.getColor(this, R.color.softBlue)
            }
            MultiChat416Theme(darkTheme = isDarkTheme.value) {
                Scaffold(topBar = {
                    ThemeAppBar(darkThemeState = isDarkTheme)
                }, modifier = Modifier.fillMaxSize()
                ) { innerPadding ->
                    mainContent(Modifier.padding(innerPadding))
                }
            }
        }
    }

    @Composable
    fun ThemeAppBar(darkThemeState: MutableState<Boolean>) {

        TopAppBar(title = {
            Row {
                Text(text = getString(R.string.app_name), modifier = Modifier.weight(8f))
                Switch(checked = darkThemeState.value, onCheckedChange = {
                    darkThemeState.value = it
                }, modifier = Modifier.weight(2f))
                IconButton(onClick = {  }) {
                    Icon(imageVector = Icons.Default.Face, contentDescription = "ChatRoom")
                }
                IconButton(onClick = { doProfile() }) {
                    Icon(imageVector = Icons.Default.ManageAccounts, contentDescription = "Profile")
                }
                IconButton(onClick = { doLogOut() }) {
                    Icon(imageVector = Icons.Default.Logout, contentDescription = "LogOut")
                }
            }
        })
    }

    private fun doProfile() {
        var intent = Intent(this@ChatRoomActivity, SettingActivity::class.java)
        startActivity(intent)
    }

    @Composable
    fun mainContent(padding: Modifier) {
        Box(
            Modifier
                .fillMaxWidth()
                .fillMaxHeight()
                .scrollable(rememberScrollableState {
                    // view world deltas should be reflected in compose world
                    // components that participate in nested scrolling
                    it
                }, Orientation.Vertical)
        ) {
        
           // compose 에서 layout 을 binding 해서 사용하는 코드 구현...
            AndroidViewBinding(ActivityChatRoomBinding::inflate) {
                var binding = this
                chatMessages.child(chatId).orderByChild("crtDtim").startAfter(startDt.toString())
                    .addChildEventListener(object : ChildEventListener{
                        override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
                            Log.e(TAG, "onChildAdded")
                            var chatMessageItem = snapshot.getValue(ChatMessage::class.java)
                            // 왜 2번씩 들어가는지 모르겠지만... 일단은 한번만 들어가게 하기 위해서
                            if (chatMessageItem != null && chatMesgItems.indexOf(chatMessageItem) < 0) {
                                chatMesgItems.add(chatMessageItem)
                            }
                            binding.rv.adapter = adapter
                            binding.rv.scrollToPosition(chatMesgItems.size - 1)
                        }

                        override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
                            Log.e(TAG, "onChildChanged")
                        }

                        override fun onChildRemoved(snapshot: DataSnapshot) {
                            Log.e(TAG, "onChildRemoved")
                        }

                        override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
                            Log.e(TAG, "onChildMoved")
                        }

                        override fun onCancelled(error: DatabaseError) {
                            Log.e(TAG, "onCancelled")
                        }

                    })
                this.sendIv.setOnClickListener {
                    if (this.contentEt.text.length > 0) {
                        var chatMessage = ChatMessage(displayName, df.format(GregorianCalendar.getInstance(TimeZone.getDefault()).timeInMillis),this.contentEt.text.toString() )
                        chatMessages.child(chatId).push().setValue(chatMessage).addOnSuccessListener {
                            Log.e(TAG, "push Success...")
                        }.addOnFailureListener {
                            Log.e(TAG, "push Failure...")
                        }
                    }
                }
            }
        }
    }

    private fun doLogOut() {
        chatMessages.child(chatId).setValue(null)
        finish()
    }
}

 

이렇게 구현을 해서 처리가 되기는 했지만, 아직 해소가 되지 않은 것은 내용을 입력 하면 realtime database에 기록이 되고, addChiledEventListener을 통해서 기록된 내용을 가져와서 recycleview에 표시를 하기 위해서 arryalist에 넣어 주는 구현을 하였는데, 입력은 1번인데 실제 표시는 2번씩 나오는 현상이 발생하였다.  아직 그 원인을 알지 못해 꼼수를 넣었다. arraylist에 이미 들어 있는 거면 넣지 않도록 하여 해소를 하였다.

 

구현된 화면 예시와 동작은 다음과 같이 처리가 되었다.

채팅방 예시

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

이렇게 까지 구현을 하면 compose 로 화면을 구현하고 예전에 만들었던 layout 을 가져와서 활용하는 것도 구현을 해 보았다.

 

 

반응형

오늘은 firebase의 real time database에 채팅방 개설을 하는 기능을 구현해 보아야겠다.  먼저 저장할 채팅방의 데이터 구조체를 구현해 보자.

 

import java.util.*

data class ChatRooms(
    var chatRooms:String = "",
    var chatTitle:String = "",
    var roomOwner:String = "",
    var chatNo:String = ""
)

들어가는 항목은 방 이름, 방제목, 방 개설자, 방 번호(이건 key로 사용할 것)

 

firebase의 realtime database 연동을 위한 준비는 이전에 posting 했던 글이나, 구글에서 찾아보면 많이 나오고 있으므로 생략...

 

다음은 데이터를 가져오고 저장하는 것을 구현하기 위해서 viewmodel을 하나 만들었다.  

 

jetpack compose 을 이용해서 setContent로 만든 화면은 앱이 시작될 때 구성이 마무리되기 때문에 화면 구성이 된 이후에 데이터를 화면에 보여주는 작업을 하기 위해서 onCreate에서 데이터를 읽어오고 하는 것을 해 보기는 했는 데, 데이터가 online으로 받아서 저장을 하는 것이다 보니, 화면이 구성된 이후에는 변화가 생기지 않았다.

 

그래서 구글 검색을 통해서 확인한 방법은 viewmodel을 이용하여 구현하는 방법이 있는 것을 알게 되었다.

 

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import kotlin.coroutines.suspendCoroutine

class ListViewModel: ViewModel() {
    private val database = Firebase.database
    private val chatroom = database.getReference("ChatRooms")
    var charItems = mutableStateListOf<ChatRooms>()
        private set

    fun addItem(chatRooms: ChatRooms) {
        chatroom.child(chatRooms.chatNo).setValue(chatRooms)
            .addOnSuccessListener {
                Log.e("setValue", "success")
                viewAllItem()
            }
            .addOnFailureListener { Log.e("setValue", "error") }
    }
    fun removeItem(chatRooms: ChatRooms) {
        chatroom.child(chatRooms.chatNo).setValue(null)
            .addOnSuccessListener {
                Log.e("setValue", "delete success")
                viewAllItem()
            }
            .addOnFailureListener { Log.e("setValue", "error") }
    }
    fun viewAllItem() {
        chatroom.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                charItems.clear()
                dataSnapshot.children.map { snapshot ->
                    charItems.add(snapshot.getValue(ChatRooms::class.java)!!)
                }
            }
            override fun onCancelled(error: DatabaseError) {}
        })
    }
}

viewmodel에 정의 함수는 addItem, removeItem, viewAllItem 딱 3개의 함수만 있다. 이것으로 데이터를 저장하고, 삭제하고, 전체 조회를 구현하고 하는 기능은 다 구현이 된다. update 기능의 경우는 realtime database의 경우는 key만 동일하다면 setValue을 통해서 처리가 가능하기 때문에 따로 구현하지 않았다.

 


import android.content.DialogInterface
import android.content.DialogInterface.BUTTON_NEGATIVE
import android.content.DialogInterface.BUTTON_POSITIVE
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.navigation.compose.rememberNavController
import com.billcoreatech.multichat416.databean.ChatRooms
import com.billcoreatech.multichat416.databean.ListViewModel
import com.billcoreatech.multichat416.databinding.MakeChatroomLayoutBinding
import com.billcoreatech.multichat416.ui.theme.MultiChat416Theme
import com.billcoreatech.multichat416.widget.*
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : ComponentActivity() {

    var TAG = "MainActivity"

    lateinit var googleSignInClient: GoogleSignInClient
    lateinit var auth: FirebaseAuth
    lateinit var sp: SharedPreferences
    private val chatroomViewModel by viewModels<ListViewModel>()
    lateinit var today:Calendar
    lateinit var sdf:SimpleDateFormat

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gso = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()

        googleSignInClient = GoogleSignIn.getClient(this, gso)
        auth = Firebase.auth
        sp = getSharedPreferences("MultiChat", MODE_PRIVATE)
        sdf = SimpleDateFormat("yyyyMMddHHmmss")
        if (auth.currentUser == null) {
            var intent = Intent(this@MainActivity, GoogleSignIn::class.java)
            startActivity(intent)
            finish()
        }

        chatroomViewModel.viewAllItem()

        setContent {
            val isDarkTheme = remember { mutableStateOf(false) }
            val navController = rememberNavController()
            if(isDarkTheme.value){
                this.window.statusBarColor = ContextCompat.getColor(this, R.color.softBlack)
            }else{
                this.window.statusBarColor = ContextCompat.getColor(this, R.color.softBlue)
            }
            MultiChat416Theme(darkTheme = isDarkTheme.value) {
                Scaffold(topBar = {
                    ThemeAppBar(darkThemeState = isDarkTheme)
                },floatingActionButton = {
                    FloatingActionButton(onClick = {
                        doMakeChatRoom()
                    }) {
                        Icon(imageVector = Icons.Default.Add, contentDescription = "add ChatRoom"
                        )
                    }
                }
                ) { innerPadding ->
                    mainContent(Modifier.padding(innerPadding))
                }
            }
        }
    }

    @Composable
    fun mainContent(padding: Modifier) {
        LazyColumnDemo(chatroomViewModel.charItems,
            onClick = {
            Log.e(TAG, "${it.chatNo}")
        },  onDelete = {
            if (it.roomOwner.contentEquals(auth.currentUser?.displayName.toString())) {
                Log.e(TAG, "delete ${it.chatNo}")
                chatroomViewModel.removeItem(it)
            }
        })
    }

    @Composable
    fun ThemeAppBar(darkThemeState: MutableState<Boolean>) {
        TopAppBar(title = {
            Row {
                Text(text = getString(R.string.app_name), modifier = Modifier.weight(8f))
                Switch(checked = darkThemeState.value, onCheckedChange = {
                    darkThemeState.value = it
                }, modifier = Modifier.weight(2f))
                IconButton(onClick = { doLogOut() }) {
                    Icon(imageVector = Icons.Default.Home, contentDescription = "Home")
                }
                IconButton(onClick = { doLogOut() }) {
                    Icon(imageVector = Icons.Default.Face, contentDescription = "Facebook")
                }
                IconButton(onClick = { doLogOut() }) {
                    Icon(imageVector = Icons.Default.Logout, contentDescription = "LogOut")
                }
            }
        })
    }

    private fun doMakeChatRoom() {
        var binding = MakeChatroomLayoutBinding.inflate(layoutInflater)
        var alertDialogBuilder = AlertDialog.Builder(this, R.style.ThemeDialog)
            .setTitle(getString(R.string.titleMakeChatRoom))
            .setView(binding.root)
            .setPositiveButton(getString(R.string.OK), DialogInterface.OnClickListener{dialogInterface, i ->
                today = Calendar.getInstance(Locale.KOREA)
                var chatRoom = ChatRooms(binding.editRoomNm.text.toString(),
                                  binding.editTitle.text.toString(),
                                  auth.currentUser?.displayName.toString(),
                                  sdf.format(today.timeInMillis))

                chatroomViewModel.addItem(chatRoom)
                Log.e(TAG, ".....")
            })
            .setNegativeButton(getString(R.string.CANCEL), DialogInterface.OnClickListener{ dialogInterface: DialogInterface, i: Int ->

            })
        var alertDialog = alertDialogBuilder.create()
        alertDialog.show()
        alertDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        alertDialog.getButton(BUTTON_POSITIVE).setTextColor(getColor(R.color.softBlue))
        alertDialog.getButton(BUTTON_NEGATIVE).setTextColor(getColor(R.color.softRed))
    }

    private fun doLogOut() {
        googleSignInClient.signOut().addOnCompleteListener( OnCompleteListener  {
                task -> if (task.isComplete ) {
                Log.e(TAG, "finish ... " )
                auth.signOut()
                finish()
            }
        })
    }

}

 MainActivity 가 이전 posting 과 달라지는 것은

chatroomViewModel by viewModels<ListViewModel>()

viewmodel을 생성하고 데이터를 읽어오기 위해서 

chatroomViewModel.viewAllItem()

데이터를 조회한 부분과

@Composable
fun mainContent(padding: Modifier) {
    LazyColumnDemo(chatroomViewModel.charItems,
        onClick = {
        Log.e(TAG, "${it.chatNo}")
    },  onDelete = {
        if (it.roomOwner.contentEquals(auth.currentUser?.displayName.toString())) {
            Log.e(TAG, "delete ${it.chatNo}")
            chatroomViewModel.removeItem(it)
        }
    })
}

mainContent 함수를 이용해서 LazyColumn에 데이터를 넣어주는 부분이 달라진다. 그리고 이번에는 LazyColumn 울 이용해서 화면에 데이터를 보여줄 view을 구현하는 부분인데, 아래와 같이 새로 하나 만들어 구현하였다.

 


import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.Composable
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.billcoreatech.multichat416.databean.ChatRooms

@Composable
fun LazyColumnDemo(charItems: SnapshotStateList<ChatRooms>,
                   onClick:(ChatRooms) -> Unit,
                   onDelete:(ChatRooms) -> Unit
) {
    Log.e("LazyColumnDemo", "${charItems.size}")
    LazyColumn(
        modifier = Modifier.fillMaxWidth(),
        contentPadding = PaddingValues(horizontal = 2.dp)
    ) {
        items(
            items = charItems,
            itemContent = {
                UserListItem(chatRooms = it, onClick = {onClick(it)}, onDelete = {onDelete(it)})
            })
    }
}

@Composable
fun UserListItem(chatRooms: ChatRooms,
                 onClick:() -> Unit,
                 onDelete:() -> Unit
    ) {
    Card(
        modifier = Modifier
            .padding(top = 10.dp)
            .fillMaxWidth(),
        elevation = 4.dp
    ) {
        Column(modifier = Modifier
            .padding(16.dp)
            .fillMaxWidth()
        ) {
            TextButton(
                onClick = { onClick() },
                content = {
                    Text(
                        text = chatRooms.chatTitle,
                        style = TextStyle(
                            color = Color.Blue,
                            fontSize = 24.sp,
                            fontWeight = FontWeight.Bold
                        )
                    )
                }
            )
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = chatRooms.chatRooms,
                    style = TextStyle(
                        color = Color.Black,
                        fontSize = 16.sp
                    )
                )
                Spacer(modifier = Modifier.padding(16.dp))
                Text(
                    text = chatRooms.roomOwner,
                    style = TextStyle(
                        color = Color.Blue,
                        fontSize = 16.sp
                    )
                )
                IconButton(onClick = { onDelete() } ) {
                    Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete" )
                }
            }
        }
    }
}

 

이제 구현된 화면의 예시를 보면 다음과 같다.

채팅 등록 화면

 

기능을 구현하는 과정에서 저번 posting 에서 달아 두었던 타이틀과 버튼들은 제거하고 topappbar을 달고 아이콘 버튼을 달았다.  다음에는 이 아이콘 버튼에 기능을 하나씩 달아보아야겠다.

 

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

이렇게 해서 채팅방을 생성하는 화면을 구현해 보았다.  이제 다음번에는 채팅창을 구현해 보아야겠다.  그리고 원래 목적인 다국어 채팅을 위한 번역 API 사용 방법도 찾아보아야겠다.

 

 

반응형

지난번에는 로그인하는 화면을 만들었으니, 이번에는 로그인해서 나오는 메인을 구현해 볼 요량이다. 

메인화면 예시

 

메인화면이라고는 뭐 아직 버튼 2개와 타이틀 하나를 달았을 뿐이다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

이것이 그냥 Layout 을 이용해서 작업을 하고 있다면 조금은 더 쉽고 빠르게 될 것 같기는 하나, 이왕 배우기 시작한 jetpack compose을 활용해서 만들어 보기로 했다.

 


import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.billcoreatech.multichat416.ui.theme.MultiChat416Theme
import com.billcoreatech.multichat416.widget.buttonAddChatRoom
import com.billcoreatech.multichat416.widget.buttonLogOut
import com.billcoreatech.multichat416.widget.titleView
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.tasks.OnCompleteListener
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase

class MainActivity : ComponentActivity() {

    var TAG = "MainActivity"
    lateinit var database : FirebaseDatabase
    lateinit var chatroom : DatabaseReference

    lateinit var googleSignInClient: GoogleSignInClient
    lateinit var auth: FirebaseAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gso = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()

        database = Firebase.database
        chatroom = database.getReference("ChatRooms")
        googleSignInClient = GoogleSignIn.getClient(this, gso)
        auth = Firebase.auth

        setContent {
            MultiChat416Theme {
                titleView(getString(R.string.titleChatRoom))
                buttonAddChatRoom(applicationContext) {

                }

                buttonLogOut(applicationContext) {
                    doLogOut()
                }

            }
        }
    }

    private fun doLogOut() {
        googleSignInClient.signOut().addOnCompleteListener( OnCompleteListener  {
                task -> if (task.isComplete ) {
                Log.e(TAG, "finish ... " )
                auth.signOut()
                finish()
            }
        })
    }

}

 

MainActivity 에는 이제 꼭 필요한 코드만 들어가고 아무것도 없다. 화면에 구현된 타이틀 (titleView) 과 버튼 2개는 따로 빼서 class을 만들었다. 

 

먼저 제목을 보여주는 titleView 의 코드

 

다른 activity 에서도 활용을 하기 위해서 parameter로 제목 이름을 받고 그것을 전체 화면 상단 오른쪽에 표시하도록 하였다.


import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun titleView(title:String) {

    Column(modifier = Modifier
        .fillMaxHeight()
        .fillMaxWidth()
        .padding(16.dp),
    verticalArrangement = Arrangement.Top,
    horizontalAlignment = Alignment.Start,
    ){
        Card(modifier = Modifier
            .width(170.dp)
            .height(60.dp)
            .padding(5.dp),
            shape = RoundedCornerShape(20.dp),
            border = BorderStroke(width = 2.dp, color = Color.White),
        ) {
            Text(text = title, color = Color.Blue
                , modifier = Modifier.padding(10.dp))
        }
    }
}

 

다음은 화면 아래쪽에 있는 Floating Button 의 코드

 

버튼에 표시할 테스트를 string.xml 에서 가져오기 위해서 context을 전달했고,  버튼을 클릭했을 때 동작을 위에서 하기 위해 onClick 함수도 만들어 썼다.


import android.content.Context
import androidx.compose.foundation.layout.*
import androidx.compose.material.ExtendedFloatingActionButton
import androidx.compose.material.FloatingActionButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.billcoreatech.multichat416.R

@Composable
fun buttonAddChatRoom(
    context: Context,
    onClick: () -> Unit
) {
    var context = LocalContext.current
    Column(modifier = Modifier
        .fillMaxHeight()
        .fillMaxWidth()
        .padding(16.dp),
        verticalArrangement = Arrangement.Bottom,
        horizontalAlignment = Alignment.End
    ){
        ExtendedFloatingActionButton(
            backgroundColor = Color.White,
            contentColor = Color.Blue,
            icon = { Icon(Icons.Filled.Add,"") },
            text = { Text(context.getString(R.string.addChatRoom)) },
            onClick = { onClick() },
            elevation = FloatingActionButtonDefaults.elevation(8.dp)
        )
    }
}

 

다음은 화면 상단에 있는 Logout 버튼

 

이 버튼 소스에서 context 을 전달해서 string.xml의 글자를 보여주도록 하였고, 버튼 click 처리를 하기 위해서 onClick을 전달했다. (사실은 받아와서 처리할 수 있도록 구현은 MainActivity에서...)

import android.content.Context
import androidx.compose.foundation.layout.*
import androidx.compose.material.ExtendedFloatingActionButton
import androidx.compose.material.FloatingActionButtonDefaults
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Logout
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.billcoreatech.multichat416.R

@Composable
fun buttonLogOut(
    context: Context,
    onClick: () -> Unit
) {
    Column(modifier = Modifier
        .fillMaxHeight()
        .fillMaxWidth()
        .padding(16.dp),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.End,
    ){
        ExtendedFloatingActionButton(
            backgroundColor = Color.White,
            contentColor = Color.Blue,
            icon = { Icon(Icons.Filled.Logout,"") },
            text = { Text(context.getString(R.string.doLogout)) },
            onClick = { onClick() },
            elevation = FloatingActionButtonDefaults.elevation(8.dp)
        )
    }
}

 

이런 분리를 하니, 재활용성이나 Copy&Paste 해서 다른 함수로 옮겨 가는 것도 도움이 될 것 같다.  아무튼 오늘도 이 거 하나 만들어 내는데, 3시간이 훌쩍~   이래서야 언제 다 끝낼 수 있을지???

 

반응형

이 나라에는 여러 나라의 사람 들어와 살고 있다.  코리안 드림을 꿈꾸며... 한 때는 이 나라의 사람들이 아메리칸드림을 꿈꾸며, 미국으로 떠났던 것처럼... 그래서 이번에는 다국적 언어를 이용한 채팅앱을 하나 만들어 볼까 한다.

 

잘 될지는 모르겠지만, 그러면서 Jetpack Compose 을 이용한 화면 구성 등에 대한 공부를 해 볼 요량이다. 

오늘은 그 처음으로 로그인 페이지를 하나 만들어 보고자 한다. 

 

로그인 페이지

이 화면을 layout 으로 그리라고 했다면

아마도 금새 그리지 않았을까 하는 생각이 든다.

 

화면에 Card box 와 Text가 들어간 button 기능 3개

제목 이름 표시 하나

 

그런데, 난 이 화면 하나를 그리기 위해서 며칠을 고민했고, 예제를 하나 찾았다. 그리고 그 예제를 참고해 가면서 화면을 그렸다.

 

그러자니, 3시간쯤... 지났다.

 

예전 project 파일에서 필요한 기능 몇개를 가지고 왔고, 그리고는 이제 완성이 되었다.

 

그냥 layout 으로 그리는 것이 나은가?  쉽게 그리는 데는 그것이 낫을 것 같기도 하다.

 

 

 

 

 

 

 

 

 

 

 

화면을 그린 source 을 살펴보자.

 


import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.preference.PreferenceManager.getDefaultSharedPreferences
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.billcoreatech.multichat416.ui.theme.MultiChat416Theme
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.UpdateAvailability
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory
import com.google.android.play.core.review.model.ReviewErrorCode
import com.google.android.play.core.tasks.RuntimeExecutionException
import com.google.android.play.core.tasks.Task
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory
import com.google.firebase.appcheck.safetynet.SafetyNetAppCheckProviderFactory
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import java.text.SimpleDateFormat
import java.util.*

class GoogleLogin : ComponentActivity() {

    var appUpdateManager: AppUpdateManager? = null
    var appUpdateInfoTask: Task<AppUpdateInfo>? = null
    lateinit var sp: SharedPreferences
    lateinit var editor: SharedPreferences.Editor
    lateinit var sdf: SimpleDateFormat
    lateinit var today: Calendar
    lateinit var googleSignInClient: GoogleSignInClient
    lateinit var auth: FirebaseAuth
    val MY_REQUEST_CODE = 1000
    var RC_SIGN_IN:Int = 1001
    var TAG = "GoogleLogin"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val gso = GoogleSignInOptions
            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()

        googleSignInClient = GoogleSignIn.getClient(this, gso)
        auth = Firebase.auth

        setContent {
            MultiChat416Theme {

                fun signIn() {
                    val signInIntent = googleSignInClient.signInIntent
                    startActivityForResult(signInIntent, RC_SIGN_IN)
                }

                fun doLogOut() {
                    googleSignInClient.signOut().addOnCompleteListener( OnCompleteListener  {
                            task -> if (task.isComplete ) {
                            Log.e(TAG, "finish ... " )
                            auth.signOut()
                            finish()
                        }
                    })
                }

                Column(modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth()
                    .padding(16.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ){
                    Text(text = buildAnnotatedString {
                        withStyle(style = SpanStyle(color = Color.Red)) {
                            append("M")
                        }
                        withStyle(style = SpanStyle(color = Color.Black)) {
                            append("ulti")
                        }

                        withStyle(style = SpanStyle(color = Color.Red)) {
                            append(" L")
                        }
                        withStyle(style = SpanStyle(color = Color.Black)) {
                            append("anguage")
                        }

                        withStyle(style = SpanStyle(color = Color.Red)) {
                            append(" C")
                        }
                        withStyle(style = SpanStyle(color = Color.Black)) {
                            append("hatting")
                        }
                    }, fontSize = 30.sp)
                    Spacer(Modifier.size(32.dp))
                    Card(modifier = Modifier
                        .width(200.dp)
                        .height(100.dp)
                        .padding(8.dp),
                    ) {
                        TextButton(onClick = {
                            signIn()
                        },content={
                            Text(text = getString(R.string.title_activity_google_login), color = Color.Blue)
                        })
                    }
                    Spacer(Modifier.size(8.dp))
                    Card(modifier = Modifier
                        .width(200.dp)
                        .height(100.dp)
                        .padding(8.dp),
                    ) {
                        TextButton(onClick = {
                            Toast.makeText(applicationContext,
                                getString(R.string.mesgRegistorOnlyGoogle),
                                Toast.LENGTH_SHORT
                                ).show()
                        }) {
                            Text(text = getString(R.string.doRegister), color = Color.Red)
                        }
                    }
                    Spacer(Modifier.size(8.dp))
                    Card(modifier = Modifier
                        .width(200.dp)
                        .height(100.dp)
                        .padding(8.dp),
                    ) {
                        TextButton(onClick = {
                            doLogOut()
                        }) {
                            Text(text = getString(R.string.doLogout), color = Color.Gray)
                        }
                    }

                }
            }
        }

        val firebaseAppCheck = FirebaseAppCheck.getInstance()
        firebaseAppCheck.installAppCheckProviderFactory(
            if (BuildConfig.DEBUG_MODE) {
                Log.e(TAG, "DebugAppCheckProviderFactory ...")
                DebugAppCheckProviderFactory.getInstance() // AVD 에서 적용시
                //SafetyNetAppCheckProviderFactory.getInstance() // 폰에서 적용시
            } else {
                Log.e(TAG, "SafetyNetAppCheckProviderFactory ...")
                SafetyNetAppCheckProviderFactory.getInstance() // 폰에서 적용시
            }
        )

        appUpdateManager = AppUpdateManagerFactory.create(this@GoogleLogin)
        // Returns an intent object that you use to check for an update.
        appUpdateInfoTask = appUpdateManager!!.appUpdateInfo
        doUpdateCheck()

        sp = getSharedPreferences("MultiChat", MODE_PRIVATE)
        editor = sp.edit()

        sdf = SimpleDateFormat("yyyyMMdd")
        today = Calendar.getInstance()
        if (!sp.getBoolean("REVIEW", false)) {
            editor.putString("REVIEW_DATE", sdf.format(today.timeInMillis))
            editor.commit()
        }

        // 사용하고 10일 지나가면 ...
        if ((today.timeInMillis - sdf.parse(sp.getString("REVIEW_DATE",sdf.format(today.timeInMillis))).time) / (1000 * 60 * 60 * 24) > 10) {
            var manager = ReviewManagerFactory.create(this@GoogleLogin)
            var request = manager.requestReviewFlow()
            editor.putBoolean("REVIEW", true)
            editor.commit()
            request.addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    // We got the ReviewInfo object
                    val reviewInfo = task.result
                    if (sp.getBoolean("REVIEW", false)) {
                        doReviseInfo(manager, this@GoogleLogin, reviewInfo)
                    }
                } else {
                    // There was some problem, log or handle the error code.
                    @ReviewErrorCode val reviewErrorCode = (task.getException() as RuntimeExecutionException).errorCode
                }
            }
        }
    }

    private fun doUpdateCheck() {
        // Checks that the platform will allow the specified type of update.
        appUpdateInfoTask!!.addOnSuccessListener { appUpdateInfo: AppUpdateInfo ->
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
                // This example applies an immediate update. To apply a flexible update
                // instead, pass in AppUpdateType.FLEXIBLE
                && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)
            ) {
                // Request the update.
                try {
                    doRequestUpdate(appUpdateInfo)
                } catch (e: IntentSender.SendIntentException) {
                    e.printStackTrace()
                }
            }
        }
    }

    @Throws(IntentSender.SendIntentException::class)
    private fun doRequestUpdate(appUpdateInfo: AppUpdateInfo) {
        Log.e(TAG, "do Update Start")
        appUpdateManager!!.startUpdateFlowForResult( // Pass the intent that is returned by 'getAppUpdateInfo()'.
            appUpdateInfo,  // Or 'AppUpdateType.FLEXIBLE' for flexible updates.
            AppUpdateType.IMMEDIATE,  // The current activity making the update request.
            this,  // Include a request code to later monitor this update request.
            MY_REQUEST_CODE
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == MY_REQUEST_CODE) {
            if (resultCode != RESULT_OK) {
                Log.e(TAG, "Update flow failed! Result code: $resultCode")
                // If the update is cancelled or fails,
                // you can request to start the update again.
            }
        }

        if (requestCode == RC_SIGN_IN) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            try {
                // Google Sign In was successful, authenticate with Firebase
                val account = task.getResult(ApiException::class.java)!!
                Log.e(TAG, "firebaseAuthWithGoogle: ${account.id}")
                firebaseAuthWithGoogle(account.idToken!!)
            } catch (e: ApiException) {
                // Google Sign In failed, update UI appropriately
                Log.e(TAG, "Google sign in failed ${e.message}")
            }
        }
    }

    private fun firebaseAuthWithGoogle(idToken: String) {
        val credential = GoogleAuthProvider.getCredential(idToken, null)
        auth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.e(TAG, "signInWithCredential:success")
                    val user = auth.currentUser
                    var intent = Intent(this@GoogleLogin, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithCredential:failure", task.exception)

                }
            }
    }

    private fun doReviseInfo(manager: ReviewManager, activity: Activity, reviewInfo: ReviewInfo) {
        val flow = manager.launchReviewFlow(activity, reviewInfo)
        flow.addOnCompleteListener { _ ->
            editor.putBoolean("REVIEW", false)
            editor.putString("REVIEW_DATE", sdf.format(today.timeInMillis))
            editor.commit()
        }
    }
}

다른 건 볼 꺼 없고, setContent 함수에 들어 있는 것만 보면 될 것 같다.  전체 흐름을 알아야 하기 때문에,  

 

setContent {
    // 테마이름은 개별적이므로 참고만...
    MultiChat416Theme {

.....

       // 먼저 아래로 배열을 하기 위해서 선언 linearlayout 처럼 사용...
        Column(modifier = Modifier
            .fillMaxHeight()
            .fillMaxWidth()
            .padding(16.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ){
        
            // 제목을 표시 한다. 첫글짜만, 대문자로 표시, 폰트색상도 빨간색...
            Text(text = buildAnnotatedString {
                withStyle(style = SpanStyle(color = Color.Red)) {
                    append("M")
                }
                withStyle(style = SpanStyle(color = Color.Black)) {
                    append("ulti")
                }

                withStyle(style = SpanStyle(color = Color.Red)) {
                    append(" L")
                }
                withStyle(style = SpanStyle(color = Color.Black)) {
                    append("anguage")
                }

                withStyle(style = SpanStyle(color = Color.Red)) {
                    append(" C")
                }
                withStyle(style = SpanStyle(color = Color.Black)) {
                    append("hatting")
                }
            }, fontSize = 30.sp)
            // 여백 두기
            Spacer(Modifier.size(32.dp))
            
            // button 을 구분하기 위해서 네모상자에 넣는다.
            Card(modifier = Modifier
                .width(200.dp)
                .height(100.dp)
                .padding(8.dp),
            ) {
                TextButton(onClick = {
                    .....
                },content={
                    Text(text = getString(R.string.title_activity_google_login), color = Color.Blue)
                })
            }
            
            // 여백 두기
            Spacer(Modifier.size(8.dp))
            // button 을 구분하기 위해서 네모상자에 넣는다.
            Card(modifier = Modifier
                .width(200.dp)
                .height(100.dp)
                .padding(8.dp),
            ) {
                TextButton(onClick = {
                    Toast.makeText(applicationContext,
                        getString(R.string.mesgRegistorOnlyGoogle),
                        Toast.LENGTH_SHORT
                        ).show()
                }) {
                    Text(text = getString(R.string.doRegister), color = Color.Red)
                }
            }
            
            // 여백 두기
            Spacer(Modifier.size(8.dp))
            // button 을 구분하기 위해서 네모상자에 넣는다.
            Card(modifier = Modifier
                .width(200.dp)
                .height(100.dp)
                .padding(8.dp),
            ) {
                TextButton(onClick = {
                    .....
                }) {
                    Text(text = getString(R.string.doLogout), color = Color.Gray)
                }
            }

        }
    }
}

대략적으로 이런 정도의 코드로 위에 나오는 화면을 구성을 하게 된다.  이걸 Layout으로 만들어 보면 얼마나 걸릴까?

 

아무튼 오늘은 1일 차 coding 끝.

 

 

 

다음은 채팅목록을 구현해 보겠다.  Database 은 Firebase 의 Realtime database 을 활용할 생각이다.

 

반응형

https://medium.com/@alexstyl/views-to-composables-d715b92c6055

 

From View to Composable: A Quick jump to Jetpack Compose from a Android View mindset (with Cheat…

Learn how to apply your View knowledge to speed up your Compose learning.

medium.com

 

오늘도 Jetpack Compose을 활용한 화면 구현에 대한 내용을 구글링을 통해서 보고 있는 데, 이런 정도의 자료가 있으면 도움이 될 듯하여 링크를 달아 둔다.

 

아직은 시작인 단계 이기 때문에 많은 정보를 찾아서 적어 두는 것이 나중에 배움을 구할 때 도움이 될 거 라고 생각된다.

 

 

compose cheat sheet 예시

 

하나씩 만들어 보자... 오늘도 파이팅!

반응형

앞에서 python 코드를 이용해서 random 숫자를 만들고 FCM 전송하는 코드를 구현해 보았다면, 이번에 그걸 이용해서 수신하는 앱을 하나 만들어 볼 차례다.

 

https://billcorea.tistory.com/179

 

자작 앱 설명서 : 로또에 관심 있으세요?

https://play.google.com/store/apps/details?id=com.billcoreatech.getLotto Get Lotto 로또 번호를 드립니다. - Google Play 앱 매주 요청한 요일에 로또 번호를 무작위로 보내 드립니다. play.google.com 앱을..

billcorea.tistory.com

 

코드 구현은 kotlin으로 해 보았다.  이제 걸음마 단계이기 때문에 코드가 조금 길어질 수 도 있지만, 아직은 준비 중인 단계이기 때문에...

 

먼저 FCM을 수신하기 위해서는 firebase와 연동을 위한 gradle 구성이 필요하다.

 

import java.text.SimpleDateFormat

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
    id 'com.google.firebase.crashlytics'
    id 'kotlin-android-extensions'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.bi.......tto"
        minSdk 28
        targetSdk 32
        versionCode 10
        versionName "0.1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        debug {
            buildConfigField "Boolean", "DEBUG_MODE", "true"
        }
        release {
            buildConfigField "Boolean", "DEBUG_MODE", "false"
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    // jetPack compose add
    buildFeatures {
        viewBinding true
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }

    def archiveBuildType = ["release"]
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            if (variant.buildType.name in archiveBuildType) {
                def df = new SimpleDateFormat("yyyyMMdd")
                df.setTimeZone(TimeZone.getDefault())
                if (variant.versionName != null) {
                    String name = "GetLotto645_${df.format(new Date())}_${defaultConfig.versionCode}_${variant.versionName}.apk"
                    output.outputFileName = name
                }
            }
        }
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'com.google.android.play:core:1.10.3'
    
    // 파이어 베이스 연동을 위한 설정...
    implementation platform('com.google.firebase:firebase-bom:29.2.1')
    // 메시징
    implementation 'com.google.firebase:firebase-messaging:23.0.2'
    // 인증처리
    implementation 'com.google.firebase:firebase-auth-ktx'
    implementation 'com.google.android.gms:play-services-auth:20.1.0'
    // realtime database
    implementation 'com.google.firebase:firebase-database-ktx'
    // crashlytics 
    implementation 'com.google.firebase:firebase-crashlytics-ktx'
    implementation 'com.google.firebase:firebase-analytics-ktx'
    // safetynet 앱 인증
    implementation 'com.google.firebase:firebase-appcheck-safetynet:16.0.0-beta05'
    implementation 'com.google.firebase:firebase-appcheck-debug:16.0.0-beta05'
    
    implementation 'androidx.preference:preference-ktx:1.2.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation "androidx.core:core-ktx:1.7.0"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.android.gms:play-services-ads:20.6.0'

    implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
    implementation 'com.google.zxing:core:3.4.1'

}

 

다음은 manifest에 intenet 활용을 위한 permission 선언이 필요하고.

 

<uses-permission android:name="android.permission.INTERNET" />

그리고 service을 등록해야 한다. FCM 수신을 위한 리시버...

<service
    android:name="com.billcoreatech.getLotto.utils.FcmReceiveService"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

 

다음은 kotlin으로 구현한 service 코드 (사실 개발자 문서의 내용을 그대로 옮겨 왔다고 해도 과언은 아닐 것이다.)

package com.b...................to.utils

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.media.RingtoneManager
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import com.billcoreatech.getLotto.MainActivity
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import getLotto.R

class FcmReceiveService : FirebaseMessagingService() {

    var TAG:String = "FcmReceiveService"

    override fun onMessageReceived(remoteMessage: RemoteMessage) {

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.e(TAG, "From: " + remoteMessage.from)

        // Check if message contains a data payload.
        if (remoteMessage.data.size > 0) {
            Log.e(TAG, "Message data payload: " + remoteMessage.data)
            sendNotification(remoteMessage.data["body"])
            var sp = getSharedPreferences("Messageing", MODE_PRIVATE)
            var editor = sp.edit()
            editor.putString("SendMsg", remoteMessage.data["body"]);
            editor.putBoolean("msgSet", true)
            editor.commit()
        }

        // Check if message contains a notification payload.
        if (remoteMessage.notification != null) {
            Log.e(
                TAG, "Message Notification Body: " + remoteMessage.notification!!.body
            )
            sendNotification(remoteMessage.notification!!.body)
        }
        onDeletedMessages()
    }

    // [END receive_message]
    override fun onNewToken(token: String) {
        Log.e(TAG, "Refreshed token: $token")

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // FCM registration token to your app server.
        sendRegistrationToServer(token)
    }
    // [END on_new_token]
    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private fun handleNow() {
        Log.d(TAG, "Short lived task is done.")
        val intent = Intent(this@FcmReceiveService, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM registration token with any
     * server-side account maintained by your application.
     *
     * @param token The new token.
     */
    private fun sendRegistrationToServer(token: String) {
        // TODO: Implement this method to send token to your app server.
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private fun sendNotification(messageBody: String?) {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        Log.e(TAG, "mesg=${messageBody}")

        val pendingIntent = PendingIntent.getActivity(
            this, 0 /* Request code */,
            intent, PendingIntent.FLAG_IMMUTABLE
        )
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val channelId = getString(R.string.default_notification_channel_id)
        val channelName: CharSequence = getString(R.string.default_notification_channel_name)
        val importance = NotificationManager.IMPORTANCE_LOW
        val notificationChannel = NotificationChannel(channelId, channelName, importance)
        notificationChannel.enableLights(true)
        notificationChannel.lightColor = Color.BLUE
        notificationChannel.enableVibration(true)
        notificationChannel.vibrationPattern =
            longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
        notificationManager.createNotificationChannel(notificationChannel)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_logo645_foreground)
            .setContentTitle(getString(R.string.fcm_message))
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .extend(
                NotificationCompat.WearableExtender()
                    .setBridgeTag("Foo")
                    .setContentIcon(R.mipmap.ic_logo645_foreground)
            )
            .setContentIntent(pendingIntent)

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }

        // Dismiss notification once the user touches it.
        notificationBuilder.setAutoCancel(true)
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
    }

}

필요한 부분만 일부 수정을 했다.

 

이번에 또 알게 된 부분이라면 전송할 때 코드 구현에 따라 수신되는 위치가 달라진다는 것이다. 

 

<data로 구현했을 때>

def lambda_handler(token, context):
    FCMToken = token

    Data = {'data': {'title': 'Lotto 보내 드립니다.', 'body': context}, 'to': FCMToken}
    Headers = {'Content-type': 'application/json',
               'Authorization': 'Key=AAAAR_..........................3uTasJ-DGfJKZkS-ccyNr0xhRHTepcuk4GaFoNMTADl4jvNFM1HYIRqzSLs219BxVA-T9frSd3VCSUIRXXn1PSxhOKgqroBVqTaxmWk'}
    http = urllib3.PoolManager().request('POST', 'https://fcm.googleapis.com/fcm/send', headers=Headers,
                                         body=json.dumps(Data))

    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}

 

<notification으로 구현했을 때>

def lambda_handler(token, context):
    FCMToken = token

    Data = {'notification': {'title': 'Lotto 보내 드립니다.', 'body': context}, 'to': FCMToken}
    Headers = {'Content-type': 'application/json',
               'Authorization': 'Key=AAAAR_0..........................uTasJ-DGfJKZkS-ccyNr0xhRHTepcuk4GaFoNMTADl4jvNFM1HYIRqzSLs219BxVA-T9frSd3VCSUIRXXn1PSxhOKgqroBVqTaxmWk'}
    http = urllib3.PoolManager().request('POST', 'https://fcm.googleapis.com/fcm/send', headers=Headers,
                                         body=json.dumps(Data))

    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}

같은 코드 이기는 하지만, 전송하는 parameter에 따라서 그걸 수신 앱에서는 다른 처리를 할 수 있다는 것이 된다. 

그래서 앞으로는 필요에 따라서 parameter을 다르게 해서 전송할 생각이다. 

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

두 영상의 미묘한 차이를 찾을 수 있을까???   위에 기술한 fcmReceiceService 코드를 같이 보면서 이해를 해 보면 작은 차이을 알 수 있지 않을까 싶다.

 

오늘도 즐 코딩 ...

반응형

https://play.google.com/store/apps/details?id=com.billcoreatech.getLotto

 

Get Lotto 로또 번호를 드립니다. - Google Play 앱

매주 요청한 요일에 로또 번호를 무작위로 보내 드립니다.

play.google.com


앱을 하나 또 게시했어요. 기능 구현을 위해서 firebase을 사용하고
번호 전달을 위해 python을 이용했습니다.  random 번호를 추출하기 때문에 당첨이 되거나 하지는 않겠지만, 
python을 이용해서 firebase readtime database을 활용하는 방법이 나올 듯합니다. 

 

또한 24시간 365일 컴터 하나를 켜 두어야 하는데, 그럴 수는 없으니, rasberry pi 3을 사용하기로 했습니다. 

os는 linux 계열을 사용했고요. 

 

crontab에 등록을 해 두었기 때문에 매일 반복적인 작업이 가능합니다. 

앱 설명서


게시된 앱의 설명이에요.

이제 random 을 이용해서 숫자를 만들고 전송하는 python code을 살펴볼게요...

import datetime
import json
import random
import sqlite3

# 2021.11.13 FCM 전송을 위한 수정
import firebase_admin
import requests
import telegram
import urllib3
from bs4 import BeautifulSoup
from firebase_admin import credentials
from firebase_admin import db

# 로컬에 저장을 해 두기 위해서 python 코드로 sqlite 테이블 만들어서 사용
conn = sqlite3.connect("opDeGangDB.sqlite", isolation_level=None)
# 커서 획득
rs = conn.cursor()
# 테이블 생성 (데이터 타입은 TEST, NUMERIC, INTEGER, REAL, BLOB 등)
rs.execute(''' CREATE TABLE IF NOT EXISTS LottoResult
              (id integer PRIMARY KEY, 
              hei text, 
              num1 text, 
              num2 text, 
              num3 text, 
              num4 text, 
              num5 text, 
              num6 text, 
              bonus text)
    ''')

# 저장된 마지막 회차를 구하기 위해서 
# 저장된 값이 string 이라서 int 타입으로 변환해서 찾음.
rs.execute('''
        select max(cast(hei as integer)) from LottoResult
    ''')
getHei = rs.fetchone()[0]

print(getHei)

# 마지막 회차는 삭제 
# 아래에서 다시 받음.
rs.execute('''
    delete from LottoResult
    where hei = {0}
'''.format(getHei))

# 동행복권 사이트에서 당첨 숫자를 파싱 하기 위해서
def getNumParase(getNum):
    # print(getNum)
    x = getNum.split('+')
    bonus = x[1].replace('.','')
    num = x[0].split(',')
    num.append(bonus)
    return num

# 동행복권 사이트 읽어오기
# 1등 당첨 번호만 마자막 회차와 다음 회차를 구함
# 그래야 최종 당첨 회차까지 구해짐.
baseUrl = "https://dhlottery.co.kr/gameResult.do?method=byWin"
for id in range(getHei, getHei+2):
    parameter = {'drwNo': id}
    res = requests.post(baseUrl, params=parameter)
    bs = BeautifulSoup(res.text, 'html.parser')
    desc = bs.find(id="desc")
    getText = desc['content']
    getNow = getText.split(' ')[1].replace('회','')
    getNum = getNumParase(getText.split(' ')[3])
    print(getNow + " " + str(getNum))

    # 한번 구해진 다음에는 null 이 오는 경우가 있어서
    try:
        rs.execute(''' 
            insert into LottoResult (hei, num1, num2, num3, num4, num5, num6, bonus)
            values ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7})
        '''.format(getNow, getNum[0], getNum[1], getNum[2], getNum[3], getNum[4], getNum[5], getNum[6]))
    except:
        pass

token = "2052..........................FBZM71o"
id = "8.....0"

# 텔레그램 봇으로 실행 되고 있음을 알려 주기 위해서...
bot = telegram.Bot(token)
now = datetime.datetime.now()

androidMsg = "이번 주({0}) 로또 번호를 알려 드려요...\n".format(now)
bot.sendMessage(chat_id=id, text=androidMsg)

# randint 을 이용해서 숫자 만들기
def getNum():
    number = []
    for i in range(0, 6):
        iNo = random.randint(1, 45)
        try:
            number.index(iNo)
        except:
            number.append(iNo)
    return number

# 여기서 5회차 분의 숫자를 구함.
def getLotto645(androidMsg):
    for i in range(0, 5):
        while True:
            numX = getNum()
            numX.sort()
            if len(numX) == 6:
                break
        androidMsg += json.dumps(numX) + "\n"

    return androidMsg

bot.sendMessage(chat_id=id, text="행복한 한 주 되세요")

#Firebase database 인증 및 앱 초기화
cred = credentials.Certificate('./services_firebase.json')
firebase_admin.initialize_app(cred,{
    'databaseURL' : 'https://getlo.....................atabase.app'
})

# FCM 전송을 하기 위해서 구한 함수 medium.com 에서 구함.
def lambda_handler(token, context):
    FCMToken = token

    Data = {'data': {'title': 'Lotto 보내 드립니다.', 'body': context}, 'to': FCMToken}
    Headers = {'Content-type': 'application/json',
               'Authorization': 'Key=AAAAR_0M6y...................xVA-T9frSd3VCSUIRXXn1PSxhOKgqroBVqTaxmWk'}
    http = urllib3.PoolManager().request('POST', 'https://fcm.googleapis.com/fcm/send', headers=Headers,
                                         body=json.dumps(Data))

    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}

# 전송해줄 요일을 구하기 위해서.
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
weekDay = datetime.datetime.today().weekday()

# firebase 에 저장된 사용자 정보 획득.
userInfo = db.reference('UserInfo')
sendNumber = db.reference('sendNumber')

# print(type(userInfo.get()))
for val in userInfo.get().values():
    # 오늘 보내야 하는 것만 보냄.
    if val["weeklyReceived"] in days[weekDay]:
        androidMsg = ""
        # 범호를 구하고
        androidMsg = getLotto645(androidMsg)
        # 번호를 보내주고
        lambda_handler(val['userToken'], androidMsg)
        print('send to ' + val['userToken'] + " " + val["weeklyReceived"] + " sendNumber(" + androidMsg + ")")
        # 보내준 번호 기록
        sendNumber.update({val['accountId'] : {'accountId': val['accountId'], 'sendNumber': androidMsg, 'sendDateTime': '{0}'.format(datetime.datetime.now())}})

# 작업 끝.
print('END JOB ...')

자료 전송을 위해서 SQlite을 이용해서 파싱 된 데이터를 참조해서 로또 당첨 번호를 기록해 두고 있어요.  

 

중간에 lambda_handler 함수는 다른 분이 posting 하신 코드를 참조해서 FCM 전송을 하고 있는데, 설정만 잘하면 전송하는 것은 문제가 없이 잘 사용하고 있습니다. 

https://medium.com/@sunyi233/python%EC%9C%BC%EB%A1%9C-fcm-push-%EB%B3%B4%EB%82%B4%EA%B8%B0-431b7a17c151

 

Python으로 FCM push 보내기

Firebase엔 FCM이라는 Push 서비스가 있습니다. 간단한 설정으로 안드로이드 앱이나 아이폰 앱에 push를 보낼 수 있습니다.

medium.com

 

다음 posting에서는 안드로이드 앱에 관한 부분을 기술해 볼게요.

 

좋은 일이 있기를 바라요.

반응형

+ Recent posts