#android #kotlin #notificationmanager
Вопрос:
Я создал базовое приложение, в котором есть два действия для уведомления об обучении, основное действие используется для нажатия кнопки, запускающей счетчик циклов (который я создал в потоке, отличном от основного потока). Затем другое действие используется для простого перехода к другому действию, когда выполняется основное действие.
Мои проблемы :
Я создал уведомление, которое вызываю в новом потоке, когда счетчик равен 50, но когда уведомление создано и я нажимаю на него, оно приводит меня к намерению (я указал через PendingIntent) Активность, но текущее состояние пользовательского интерфейса потеряно.
Что я сделал :
Я добавил флаг намерения «FLAG_ACTIVITY_CLEAR_TOP» к объекту намерения, но это не сработало, я добавил PendingIntent.FLAG_UPDATE_CURRENT, но это все равно не сработало
Чего я хочу достичь :
Когда уведомление запущено, я хочу видеть текущее начало подсчета циклов, когда уведомление нажато и ожидаемая активность открыта системной службой.
Мой код : Класс уведомлений
fun NotificationManager.sendNotification(message : String, applicationContext : Context){
val NOTIFICATION_ID = 0
// creat an intent for the notification using pendingIntent
val contentIntent = Intent(applicationContext, MainActivity::class.java)
contentIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
// create a pendingIntent object
val pendingIntent = PendingIntent.getActivity(applicationContext, NOTIFICATION_ID,
contentIntent, PendingIntent.FLAG_UPDATE_CURRENT)
// create a notification
val builder = NotificationCompat.Builder(
applicationContext,
applicationContext.getString(R.string.get_channel_id)
)
.setSmallIcon(R.drawable.ic_fun)
.setContentTitle("My notification")
.setContentText(message)
.setContentIntent(pendingIntent)
notify(NOTIFICATION_ID, builder.build())
}
Основная деятельность
package com.example.anew
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.example.anew.utils.sendNotification
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
private lateinit var noti_btn : Button
private lateinit var tv : TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
createChannel(getString(R.string.get_channel_id), getString(R.string.get_channel_name))
tv = findViewById(R.id.textView)
noti_btn = findViewById(R.id.noti_btn)
noti_btn.setOnClickListener {
counter()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.mi_start -> {
startActivity(Intent(this, WorldView::class.java))
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun counter(){
// this method is used to update the count on the ui, so to avoid blocking the ui, i created a new thread,
// this will make my looping to run on a seperate thread and thus not blocking the mainuithread, giving
val hi_no = 1000
var counter = 0
var flag = true
var see = Thread{
while (flag){
Thread.sleep(1000)
runOnUiThread{
tv.text = " Counting up $counter "
}
counter
if (counter == 50){
startNotification()
}
if (counter == hi_no){
flag = false
}
}
}
see.start()
}
private fun createChannel(c_id: String, c_name: String) {
// here we create our notificationChannel, the notificationChannel takes the channel_id and
// channel_name as parameters, we also have to call the methods we want on it like setColor etc
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notification_channel = NotificationChannel(c_id, c_name, NotificationManager.IMPORTANCE_LOW)
notification_channel.enableLights(true)
notification_channel.lightColor = Color.CYAN
notification_channel.enableVibration(true)
notification_channel.description = "My first notification"
// get the instance of the NotificationManager and connect the notificationChannel to it
val notification = getSystemService(NotificationManager::class.java)
notification.createNotificationChannel(notification_channel)
}
}
private fun startNotification() {
// in other to start a notification or stop one,
// we have to get an instance of that notificationManager using systemService
val notification = ContextCompat.getSystemService(this, NotificationManager::class.java)
notification?.sendNotification("Continue to pray", this)
}
}