Question

I'm trying to find a way to automatically add a widget without making the user add it manually via the launcher to the home page or lock screen (preferably both, but at minimum to the lock screen).

Here's what I have to add the widget to the home screen. What am I missing?

 public class MyWidgetProvider extends AppWidgetProvider {

   private static final String ACTION_CLICK = "ACTION_CLICK";

   @Override
   public void onUpdate(Context context, AppWidgetManager appWidgetManager,
       int[] appWidgetIds) {


     ComponentName thisWidget = new ComponentName(context,
         MyWidgetProvider.class);
     int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
     final List<AppWidgetProviderInfo> infos = appWidgetManager.getInstalledProviders();


     AppWidgetProviderInfo appWidgetInfo = null;

     for (final AppWidgetProviderInfo info : infos) {
    Log.v("AD3", info.provider.getPackageName() + " / "
            + info.provider.getClassName());
}

     for (final AppWidgetProviderInfo info : infos) {
         if (info.provider.getClassName().equals(thisWidget.getClassName()) && info.provider.getPackageName().equals(thisWidget.getPackageName())) {

        appWidgetInfo = info;
        break;
         }
     }
     if (appWidgetInfo == null)
         return; //stop here

     for (int widgetId : allWidgetIds) {

       int number = (new Random().nextInt(100));

       RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
           R.layout.widget_layout);
       Log.w("WidgetExample", String.valueOf(number));
       remoteViews.setTextViewText(R.id.update, String.valueOf(number));

       Intent intent = new Intent(context, MyWidgetProvider.class);

       intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
       intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

       PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
           0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
       remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
       appWidgetManager.updateAppWidget(widgetId, remoteViews);
     }
   }
 }
Was it helpful?

Solution

You are missing the fact that this is not possible. There is no API to forcibly add an app widget to a home screen or lockscreen. Not all home screens and lockscreens even support app widgets.

You are welcome to roll your own ROM mod, where your app widget is pre-installed on the home screen, the way manufacturers do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top