React Expo API 只能呈現有進度數值的通知視窗,如下列 YouTube 錄影所示。
從 AI 的回應來看,如果要進一步自訂通知視窗,需要使用 bare work flow。
使用 bare work flow,需要仰賴原生 Module 來跟 Android 原生 Notification API 互動。
先使用 AI 生成樣板代碼:
// ProgressNotificationModule.kt
package com.yourpackage.progressnotification
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
class ProgressNotificationModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
companion object {
private const val CHANNEL_ID = "progress_channel"
private const val NOTIFICATION_ID = 1
}
private val notificationManager: NotificationManager by lazy {
reactContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
init {
createNotificationChannel()
}
override fun getName(): String = "ProgressNotification"
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, "Progress Notifications", NotificationManager.IMPORTANCE_LOW)
notificationManager.createNotificationChannel(channel)
}
}
@ReactMethod
fun showProgressNotification(title: String, content: String, progress: Int) {
val builder = NotificationCompat.Builder(reactApplicationContext, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle(title)
.setContentText(content)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
if (progress in 0..100) {
builder.setProgress(100, progress, false)
}
notificationManager.notify(NOTIFICATION_ID, builder.build())
}
@ReactMethod
fun hideProgressNotification() {
notificationManager.cancel(NOTIFICATION_ID)
}
}
// ProgressNotificationPackage.kt
package com.yourpackage.progressnotification
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
class ProgressNotificationPackage : ReactPackage {
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> = emptyList()
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
listOf(ProgressNotificationModule(reactContext))
}
在 Android 目錄中,建立上述 2 個 class。
路徑參考:android/app/src/main/java/com/jim/notification/ProgressNotificationModule.kt