android widget opens application with delay when clicked

42 views Asked by At

I have a widget which opens a qr scan screen in my application but, when I click widget it opens application with delay, when I put log within onReceive function I can see the logged text after like 1-2 seconds

And problem is within that period user can click multiple times widget which will call onReceive function multiple times which is not intended

below is my widger provider

class QrScanWidgetProvider : AppWidgetProvider() {

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        for (appWidgetId in appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId)
        }
    }

    fun updateAppWidget(
        context: Context, appWidgetManager: AppWidgetManager,
        appWidgetId: Int
    ) {
        val views = RemoteViews(context.packageName, R.layout.widget_qr_scan).also {
            it.setTextViewText(R.id.tv_qr_scan, context.getString(R.string.qr_scan))
        }
        setOnItemClicks(views, context)
        appWidgetManager.updateAppWidget(appWidgetId, views)
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == ON_ITEM_CLICK_ACTION && context != null) {
            NavigationUtils.getShowScreenPendingIntent(
                context,
                SCREEN_SCAN,
                null,
                true
            ).send()
        }
        super.onReceive(context, intent)
    }

    private fun setOnItemClicks(views: RemoteViews, context: Context) {
        val onItemClickIntent = Intent(context, QrScanWidgetProvider::class.java)

        onItemClickIntent.action = ON_ITEM_CLICK_ACTION
        views.setOnClickPendingIntent(
            R.id.root_view, PendingIntent.getBroadcast(
                context, 0, onItemClickIntent,
                PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
            )
        )
    }

    companion object {
        const val ON_ITEM_CLICK_ACTION =
            "ON_ITEM_CLICK_ACTION"
    }
}
0

There are 0 answers