How to open an application from widget in Android?

Viewed 25503

When we click the widget at that time I need to open an activity screen (or application). How to do this?

5 Answers

Using Kotlin

You need to add PendingIntent on Click of your widget Views

remoteViews.setOnClickPendingIntent(R.id.widgetRoot, 
               PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))

Where widgetRoot is the id of my widget's parent ViewGroup

In On Update

Pending intent is usually added in onUpdate callback

    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray) {

        // There may be multiple widgets active, so update all of them
        val widgetIds = appWidgetManager.getAppWidgetIds( ComponentName(context, ClockWidget::class.java))
        for (appWidgetId in widgetIds) {

                // Construct the RemoteViews object
                val remoteViews = RemoteViews(context.packageName, R.layout.clock_widget)

               //Open App on Widget Click
                remoteViews.setOnClickPendingIntent(R.id.weatherRoot,  
   PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))

                //Update Widget 
                remoteViews.setTextViewText(R.id.appWidgetText, Date().toString())
                appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
            }
        }
    }

very simple(In xamarin c# android mono):

public override void OnReceive(Context context, Intent intent)
        {
            if (ViewClick.Equals(intent.Action))
            {
                var pm = context.PackageManager;
                try
                {
                    var packageName = "com.companyname.YOURPACKAGENAME";
                    var launchIntent = pm.GetLaunchIntentForPackage(packageName);
                    context.StartActivity(launchIntent);
                }
                catch
                {
                    // Something went wrong :)
                }
            }
            base.OnReceive(context, intent);

        }
Related