簡體   English   中英

等待首選項數據存儲從 workmanager 中的首選項數據存儲中檢索數據

[英]Wait for Preferences Datastore to retrieve data from preferences datastore in workmanager

我的應用程序正在后台檢查未讀電子郵件,問題是我需要在上次檢查電子郵件時保存和檢索 lastCheckedDate,以便我只能顯示新收到的電子郵件。

為了從數據存儲中檢索數據,我使用 observeLastCheckedDate() 並且我必須使用處理程序調用它,因為如果我沒有得到:

java.lang.IllegalStateException:無法在后台線程上調用觀察

Function observeLastCheckedDate() 被調用,但是當它完成(更新 lastCheckedDate)時,workManager 任務已經以未更新的 var lastchecked 日期完成。

在主要的 class 中,我通過創建和調用回調來避免這個問題,但在這里它不起作用(它使整個應用程序凍結),所以我們需要等待 function 完成或獲取一些從數據存儲中檢索數據的新方法。

 class WorkerMan(private val mContext: Context, workerParameters: WorkerParameters) :
Worker(mContext, workerParameters) {

private lateinit var settingsManager: SettingsManager
var lastCheckedDate: Long = 0

@SuppressLint("RestrictedApi", "CheckResult")
val email = inputData.getString("email")
val password = inputData.getString("password")
val token = inputData.getString("token")

fun saveLastCheckedDate(lastCheckedDate: Long) {
    GlobalScope.launch {
        settingsManager.storeLastCheckedDate(lastCheckedDate)
    }
}

 private fun observeLastCheckedDate() {
    settingsManager.lastCheckedDateFlow.asLiveData().observe(
        ProcessLifecycleOwner.get(),
        {
            this.lastCheckedDate = it
        }
    )
}

@SuppressLint("RestrictedApi", "WrongThread")
override fun doWork(): Result {
    settingsManager = SettingsManager(getApplicationContext())



    var messageCounter = 0;

    val handler = Handler(Looper.getMainLooper())
    handler.post {
        observeLastCheckedDate()
    }

  Thread.sleep(1000*10)


            println("**************************************************************************")
            println("**************************************************************************")
            println("WorkManager: Work called")
            println("WorkManager email: " + email)
            println("WorkManager: Last Checked Moment : " + lastCheckedDate.toString())
            println("WorkManager:      Current Moment : " + Instant.now().toEpochMilli())
            println("**************************************************************************")
            println("**************************************************************************")

            try {

                val session = Session.getDefaultInstance(Properties())
                val store = session.getStore("imaps")
                store.connect(
                    "mail.metropolitan.ac.rs",
                    993,
                    email,
                    password
                )
                val inbox = store.getFolder("INBOX")
                inbox.open(Folder.READ_ONLY)


                val messages = inbox.search(
                    FlagTerm(Flags(Flags.Flag.SEEN), false)
                )

                Arrays.sort(
                    messages
                ) { m1: Message, m2: Message ->
                    try {
                        return@sort m2.sentDate.compareTo(m1.sentDate)
                    } catch (e: MessagingException) {
                        throw RuntimeException(e)
                    }
                }


                for (message in messages) {
                    Thread.sleep(1000)
                    messageCounter++

                    if (message.receivedDate.toInstant().toEpochMilli() >= lastCheckedDate) {

                        Thread.sleep(1000)
                        println("=====================================================")
                        println("NOTIFIKACIJA")

                        var title = ""
                        for (element in message.from) {
                            title += element.toString().substringAfter("<").substringBefore(">")
                            title += " "
                        }
                        println("Title :" + title)
                        println("Subject :" + message.subject)
                        println("Datum i vreme : " + message.receivedDate)

                        title.replace("[", "")
                        title.replace("]", "")

                        send(token, message.subject, title)

                    }

                    if (messageCounter > 10) {
                        break

                    }

                }

                saveLastCheckedDate(Instant.now().toEpochMilli())

                println("=====================================================")
                Log.d("WorkManager", "Job finished")

            } catch (e: Exception) {
                Log.d("WorkManager error", "doWork not executed")
                Log.d("WorkManager error", "error: ")
                Log.d("WorkManager error", e.printStackTrace().toString())
            } catch (e: NetworkOnMainThreadException) {
                Log.d("WorkManager error", "doWork not executed")
                Log.d("WorkManager error", "NetworkOnMainThreadException: ")
                Log.d("WorkManager error", e.toString())
            }

    return Result.Success();
}

 }

fun send(to: String?, body: String?, title: String?): String? {
    try {
        val apiKey =
            "****************************************************************"
        val url = URL("https://fcm.googleapis.com/fcm/send")
        val conn = url.openConnection() as HttpURLConnection
        conn.doOutput = true
        conn.requestMethod = "POST"
        conn.setRequestProperty("Content-Type", "application/json")
        conn.setRequestProperty("Authorization", "key=$apiKey")
        conn.doOutput = true
        val message = JSONObject()
        message.put("to", to)
        message.put("priority", "high")
        val notification = JSONObject()
        notification.put("title", title)
        notification.put("body", body)
        message.put("notification", notification)
        val os = conn.outputStream
        os.write(message.toString().toByteArray())
        os.flush()
        os.close()
        val responseCode = conn.responseCode
        println("\nSending 'POST' request to URL : $url")
        println("Post parameters : $message")
        println("Response Code : $responseCode")
        println("Response Code : " + conn.responseMessage)
        val `in` = BufferedReader(InputStreamReader(conn.inputStream))
        var inputLine: String?
        val response = StringBuffer()
        while (`in`.readLine().also { inputLine = it } != null) {
            response.append(inputLine)
        }
        `in`.close()

        println(response.toString())
        return response.toString()
    } catch (e: Exception) {
        Log.d("WorkManager error", "send not executed")
        Log.d("WorkManager error", "error: ")
        Log.d("WorkManager error", e.printStackTrace().toString())
    } catch (e: NetworkOnMainThreadException) {
        Log.d("WorkManager error", "send() not executed")
        Log.d("WorkManager error", "NetworkOnMainThreadException: ")
        Log.d("WorkManager error", e.toString())
    }
    return "error"
}

數據存儲 class:

class SettingsManager(context: Context) {

    private val dataStore = context.createDataStore(name = "user_settings_preferencess")


    companion object {

        val ENABLE_NOTIFICATIONS = preferencesKey<Int>("ENABLE_NOTIFICATIONS")
        val ENABLE_MAIL_NOTIFICATIONS = preferencesKey<Int>("ENABLE_MAIL_NOTIFICATIONS")
        val LAST_CHECKED_DATE = preferencesKey<Long>("LAST_CHECKED_DATE")

    }


    //Store user data
    suspend fun storeNotifications(enableNotifications: Int) {
        dataStore.edit {
            it[ENABLE_NOTIFICATIONS] = enableNotifications


        }
    }

    suspend fun storeMailNotifications(enableMailNotifications: Int) {
        dataStore.edit {
            it[ENABLE_MAIL_NOTIFICATIONS] = enableMailNotifications

        }
    }

    suspend fun storeLastCheckedDate(lastCheckedDate: Long) {
        dataStore.edit {
            it[LAST_CHECKED_DATE] = lastCheckedDate


        }
    }

    val lastCheckedDateFlow: Flow<Long> = dataStore.data.map {
        it[LAST_CHECKED_DATE] ?: 0
    }
    
    val enableNotificationsFlow: Flow<Int> = dataStore.data.map {
        it[ENABLE_NOTIFICATIONS] ?: 1
    }
    val enableMailNotificationsFlow: Flow<Int> = dataStore.data.map {
        it[ENABLE_MAIL_NOTIFICATIONS] ?: 1
    }


}

這對於簡單工作的線程來說是一個巨大的混亂。 (永遠不要讓你的線程休眠等待一個值)

如果您要在工作程序 class 中使用協程。 所以不要那樣做

有一個替代的CoroutineWorker可以從中擴展您的 class 而不是Worker

它將為您提供doWork() function 的暫停版本

注意:記得添加工作管理器依賴-ktx版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM