카테고리 없음

5주차_ 짝퉁마켓 앱 3. 알림(Notificatio)

아이른 2024. 4. 16. 12:13

 

문제 1. 

  • [①] 디자인 및 화면 구성을 최대한 동일하게 해주세요. (사이즈 및 여백도 최대한 맞춰주세요.) ✨
  • [⑦] 상품 데이터는 dummy data 를 사용합니다. (더미 데이터는 자유롭게 추가 및 수정 가능)
  • [⑤] RecyclerViewer를 이용해 리스트 화면을 만들어주세요.
  • [⑤-①] 상단 툴바를 제거하고 풀스크린 화면으로 세팅해주세요. (상태바(시간/배터리 표시하는 최상단바)는 남기고)
  • [②] 상품 이미지는 모서리를 라운드 처리해주세요.
  • [③] 상품 이름은 최대 두 줄이고, 그래도 넘어가면 뒷 부분에 …으로 처리해주세요.
  • [①] 뒤로가기(BACK)버튼 클릭시 종료하시겠습니까? [확인][취소] 다이얼로그를 띄워주세요.
  • [①] 상단 종모양 아이콘을 누르면 Notification을 생성해 주세요. (예시 비디오 참고)
  • [⑥] 상품 가격은 1000단위로 콤마(,) 처리해주세요.
  • [④] 상품 아이템들 사이에 회색 라인을 추가해서 구분해주세요.
  • [ ] 상품 선택시 아래 상품 상세 페이지로 이동합니다.
  • [ ] 상품 상세페이지 이동시 intent로 객체를 전달합니다. (Parcelize 사용)

① 상단 아이콘을 누르면 Notification을 생성

1. 알림(Notification)

  • 앱의 UI와 별도로 사용자에게 앱과 관련한 정보를 보여주는 기능
  • 단말기 상단에 표시되고, 앱 아이콘의 배지로도 표시(Android 8.0부터)
    • 간단한 작업(ex. 문자 답하기) 가능(Android 7.0부터)

 

2. 알림(Notification) 사용법

  • 알림 채널(Android 8.0부터) 만들기 
val builder: NotificationCompat.Builder
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            // 26 버전 이상
            val channelId="one-channel"
            val channelName="My Channel One"
            val channel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_DEFAULT//알림 중요도
            ).apply {
                // 채널에 다양한 정보 설정
                description = "My Channel One Description"
                setShowBadge(true)//Badge:앱 아이콘에 알람 갯수 만큼 숫자 표현
                val uri: Uri = RingtoneManager.getDefaultUri(
                RingtoneManager.TYPE_NOTIFICATION)//알람 설정
                val audioAttributes = AudioAttributes.Builder()//안드로이드 기본 사운드
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build()
                setSound(uri, audioAttributes)
                enableVibration(true)//진동 설정 유무
            }
            // 채널을 NotificationManager에 등록
            manager.createNotificationChannel(channel)

            // 채널을 이용하여 builder 생성
            builder = NotificationCompat.Builder(this, channelId)

        }else {
            // 26 버전 이하
            builder = NotificationCompat.Builder(this)
        }
  • Android API 33이상
    • AndroidManifest.xml 권한 시스템 변경
    • 사용자 권한 요청
//AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">

    <!-- API 33 이상을 위한 알림 권한 추가 -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

    ...
</manifest>
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {
        // 알림 권한이 없다면, 사용자에게 권한 요청
        val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
            putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
        }
        startActivity(intent)
    }
}
  • NotificationCompat.Builder 객체에서 알림에 대한 UI정보와 작업을 지정
    • setSmallIcon() : 작은 아이콘
    • setContentTitle() : 제목
    • setContentText() : 세부텍스트
    • setStyle(NotificationCompat.BigTextStyle().bigText() : 알림 확장뷰_긴텍스트
    • setStyle(NotificationCompat.BigPictureStyle().bigPicture(bitmap).bigLargeIcon(null)) : 알림 확장뷰_이미지
    builder.run {
        setSmallIcon(R.drawable.woman)
        setWhen(System.currentTimeMillis())
        setContentTitle("키워드 알림")
        setContentText("설정한 키워드에 대한 알림이 도착했습니다!")
        /* 긴텍스트
        setStyle(NotificationCompat.BigTextStyle()
                .bigText("이것은 긴텍스트 샘플입니다. 
                아주 긴 텍스트를 쓸때는 여기다 하면 됩니다.
                이것은 긴텍스트 샘플입니다. 
                아주 긴 텍스트를 쓸때는 여기다 하면 됩니다.
        */
        setLargeIcon(bitmap)
        /* 이미지 확장
        setStyle(NotificationCompat.BigPictureStyle()
               .bigPicture(bitmap)
               .bigLargeIcon(null))
        */
        addAction(R.drawable.woman, "Action", pendingIntent)
    }
    manager.notify(11, builder.build())
  • 알림에 엑티비티 연결
    val bitmap = BitmapFactory.decodeResource(resources, R.drawable.woman)
    val intent = Intent(this, MainActivity::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    val pendingIntent = PendingIntent.getActivity(
        this,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

동작 화면

 

더보기
   class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        binding.btnNotification.setOnClickListener {
            notification()
        }

   private fun notification() {

        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        val builder: NotificationCompat.Builder
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) {

                val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
                    putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
                }
                startActivity(intent)
            }
            val channelId = "one-channel"
            val channelName = "My Channel One"
            val channel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = "My Channel One Description"
                setShowBadge(true)
                val uri: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val audioAttributes = AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build()
                setSound(uri, audioAttributes)
                enableVibration(true)
            }
            manager.createNotificationChannel(channel)
            builder = NotificationCompat.Builder(this, channelId)
        } else {
            builder = NotificationCompat.Builder(this)
        }

        val bitmap = BitmapFactory.decodeResource(resources, R.drawable.woman)
        val intent = Intent(this, MainActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        builder.run {
            setSmallIcon(R.drawable.woman)
            setWhen(System.currentTimeMillis())
            setContentTitle("키워드 알림")
            setContentText("설정한 키워드에 대한 알림이 도착했습니다!")
            setLargeIcon(bitmap)

            addAction(R.drawable.woman, "Action", pendingIntent)
        }
        manager.notify(11, builder.build())
    }

 

<a href="https://www.flaticon.com/kr/free-icons/" title="심장 아이콘">심장 아이콘 제작자: Freepik - Flaticon</a>

<a href="https://www.flaticon.com/kr/free-icons/-" title="스케이트 보드 아이콘">스케이트 보드 아이콘  제작자: Victoruler - Flaticon</a>


동작 화면