본문 바로가기
안드로이드 코틀린

[Kotlin][Android] 초대 메세지 공유하는 기능 만들기

by teamnova 2021. 11. 24.

안녕하세요! 이번 포스팅에서는 유저의 닉네임을 포함한 초대 메세지를 공유하는 기능을 만들어보겠습니다.

이 기능은 안드로이드 sdk 28에서 테스트되었습니다.

 

 

간단하게 닉네임을 작성하고, 초대 메세지를 전송할 수 있는 레이아웃을 만들어보겠습니다.

activity_invitation.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:gravity="center"
    android:orientation="vertical"

    tools:context=".InvitationActivity">

    <EditText
        android:id="@+id/edt_nickname"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:inputType="text"
        android:imeOptions="actionDone"
        android:hint="내 닉네임" />

    <Button
        android:id="@+id/btn_invitation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="초대하기" />
</LinearLayout>

 

 

다음으로, 초대하기 버튼을 클릭했을 때, 초대메세지를 전송하는 액티비티를 만들어보겠습니다.

share() 메소드는 스틱코드를 이용하면 빠르게 구현할 수 있습니다.

[AOS][Kotlin] 인텐트 활용하기 - Stickode

 

스틱코드

 

stickode.com

 

InvitationActivity.kt

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

class InvitationActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_invitation)

        findViewById<Button>(R.id.btn_invitation).setOnClickListener {
            val nickname = findViewById<EditText>(R.id.edt_nickname).text.toString()
            val message = "코드를 쉽고 빠르게 구현할 수 있다고? '$nickname'님이 당신에게 스틱코드로 초대합니다! 스틱코드에서 검증된 코드를 찾아보세요~\n\nhttps://stickode.com"
            share(message)
        }
    }

    @SuppressLint("QueryPermissionsNeeded")
    fun share(content: String) {
        val intent = Intent(Intent.ACTION_SEND) // 공유하는 인텐트 생성
            .apply {
                type = "text/plain" // 데이터 타입 설정
                putExtra(Intent.EXTRA_TEXT, content) // 보낼 내용 설정
            }

        if (intent.resolveActivity(packageManager) != null) {
            startActivity(Intent.createChooser(intent, "초대 메세지 보내기"))
        } else {
            Toast.makeText(this, "초대 메세지를 전송할 수 없습니다", Toast.LENGTH_LONG).show()
        }
    }

}

 

 

임의로 스틱코드에 초대하는 메세지로 만들어봤습니다.

원하는 메세지로 변경해서 사용해보시기 바랍니다~