[FIXED] Click widget to launch fragment Android

Issue

I am implementing a widget function and facing an issue. I tried to launch a specific fragment by a button that I made in my widget but it was not able to do it with Intent. How can I launch a fragment in a widget?

AppWidgetProvider

class WidgetProvider : AppWidgetProvider() {

override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) {
    super.onUpdate(context, appWidgetManager, appWidgetIds)
    appWidgetIds?.forEach { appWidgetId ->
        val views: RemoteViews = addViews(context)
        appWidgetManager?.updateAppWidget(appWidgetId, views)
    }
}

private fun setMyAction(context: Context?): PendingIntent {

    val intent = Intent(context, MainFragment::class.java)

    return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}

private fun buildURIIntent(context: Context?): PendingIntent {
    val intent = Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://www.google.com/"))
    return PendingIntent.getActivity(context, 0, intent, 0)
}

private fun addViews(context: Context?): RemoteViews {
    val views = RemoteViews(context?.packageName, R.layout.widget)
    views.setOnClickPendingIntent(R.id.button, setMyAction(context))
    views.setOnClickPendingIntent(R.id.button2, buildURIIntent(context))
    return views
}
}

Solution

I found out it isn’t able to move from non-fragment to a fragment by navigation/ intent. After long searching, I could find no result but I solved this problem by using a deep link.

Here I attached my code for anyone in need.

Widget to Fragment

private fun addViews(context: Context?): RemoteViews {
    val views = RemoteViews(context?.packageName, R.layout.widget)

    val  myPendingIntent = context?.let {
        NavDeepLinkBuilder(it)
            .setGraph(R.navigation.nav_graph)
            .setDestination(R.id.qrScanFragment)
            .createPendingIntent()
    }

    views.setOnClickPendingIntent(R.id.qr_btn, myPendingIntent)
    return views
}

Answered By – Lucy

Answer Checked By – Timothy Miller (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published