Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
Expand Down
95 changes: 86 additions & 9 deletions app/src/main/java/com/example/assignment02/CountFragment.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.assignment02

import android.app.Notification
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
Expand All @@ -8,13 +9,25 @@ import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import android.content.DialogInterface;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AlertDialog
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat


class CountFragment : Fragment() {

private lateinit var numberText: TextView
private lateinit var notification: Notification
private var currentNumber: Int = 0

override fun onCreateView(
Expand All @@ -39,16 +52,80 @@ class CountFragment : Fragment() {
showAlertDialog()
}
randomButton.setOnClickListener {
val randomFragment = RandomFragment.newInstance(currentNumber)
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, randomFragment)
.addToBackStack(null)
.commit()
// 숫자 전달을 위한 Intent 생성
val intent = Intent(context, MainActivity::class.java).apply {
putExtra("number", currentNumber) // 데이터를 Intent에 추가
putExtra("Notification", true) // Notification 여부 플래그 추가
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

notification = context?.let { it1 ->
NotificationCompat.Builder(it1, "assignment-7")
.setSmallIcon(android.R.drawable.ic_notification_overlay)
.setContentTitle("랜덤 숫자 (0 ~ " + currentNumber + ")")
.setContentText("새로운 랜덤 숫자가 생성되었습니다.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent) // 클릭 시 실행
.setAutoCancel(true) // 클릭 후 알림 자동 제거
.build()
}!!

showNotification()
}

return view
}

private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Assignment Notification"
val descriptionText = "Channel for Assignment notifications"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("assignment-7", name, importance).apply {
description = descriptionText
}
// NotificationManager에 채널 등록
val notificationManager: NotificationManager =
requireContext().getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}

private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
// 권한이 허용된 경우 알림 표시
showNotification()
} else {
// 권한이 거부된 경우 처리

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

권한이 거부되었을 때 사용되는 아래의 메소드도 사용해보세용

shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)

println("Notification permission denied")
}
}

// 권한등을 채크하고 Notification을 보낸다.
private fun showNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// Android 13 이상에서는 POST_NOTIFICATIONS 권한 확인
if (ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
return
}
}

// 권한이 있거나 Android 12 이하인 경우 알림 표시
NotificationManagerCompat.from(requireContext()).notify(1, notification)
}

private fun showAlertDialog() {
// Fragment에서는 requireContext()를 사용하여 컨텍스트를 가져옴
val builder = AlertDialog.Builder(requireContext())
Expand Down Expand Up @@ -84,4 +161,4 @@ class CountFragment : Fragment() {
return fragment
}
}
}
}
19 changes: 15 additions & 4 deletions app/src/main/java/com/example/assignment02/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@ package com.example.assignment02

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, CountFragment.newInstance(0))
.commit()
val isFromNotification = intent?.getBooleanExtra("Notification", false) ?: false
val data = intent?.getIntExtra("number", 0) ?: 0

val fragment: Fragment = if (isFromNotification) {
// Notification을 통해 실행된 경우 FragmentB 로드 및 데이터 전달
RandomFragment.newInstance(data)
} else {
// 기본적으로 FragmentA 로드
CountFragment.newInstance(0)
}

// 선택된 Fragment를 동적으로 할당
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
}
}
6 changes: 4 additions & 2 deletions app/src/main/java/com/example/assignment02/RandomFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ class RandomFragment : Fragment() {
currentNumber = it.getInt("randomNumber", 0)
}

currentNumber = (0..currentNumber-1).random()
if (currentNumber>=1) {
currentNumber = (0..currentNumber - 1).random()
}
number_number.text = currentNumber.toString()

requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
Expand All @@ -51,4 +53,4 @@ class RandomFragment : Fragment() {
.commit()
}
}
}
}