0

I create a button in Activty and by clicking on button I want to add Appwidget to Homescreen Programatically in android.

actually I am using appwidgethost class to add appwidget to homescreen but appwidget is added to activity not to homescreen. my code is below

package com.lgfischer.widgethost;


import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;

public class MYWidgetHostActivity extends Activity {

static final String TAG = "MYWidgetHostActivity";

AppWidgetManager mAppWidgetManager;
AppWidgetHost mAppWidgetHost;

ViewGroup mainlayout;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mainlayout = (ViewGroup) findViewById(R.id.main_layout);

    mAppWidgetManager = AppWidgetManager.getInstance(this);
    mAppWidgetHost = new AppWidgetHost(this, R.id.APPWIDGET_HOST_ID);
}

@Override
protected void onStart() {
    super.onStart();
    mAppWidgetHost.startListening();
}

/**
 * Stop listen for updates for our widgets (saving battery).
 */
@Override
protected void onStop() {
    super.onStop();
    mAppWidgetHost.stopListening();
}

public void my() {
    mAppWidgetManager = AppWidgetManager.getInstance(this);
    AppWidgetProviderInfo newAppWidgetProviderInfo = new AppWidgetProviderInfo();
    ComponentName cn = new ComponentName("com.dgflip.scada",
            "com.dgflip.service.AppWidget");
    // Get an id
    int appWidgetId = mAppWidgetHost.allocateAppWidgetId();

    // Get the list of installed widgets
    List<AppWidgetProviderInfo> appWidgetInfos = new ArrayList<AppWidgetProviderInfo>();
    appWidgetInfos = mAppWidgetManager.getInstalledProviders();

    for (int j = 0; j < appWidgetInfos.size(); j++) {
        if (appWidgetInfos.get(j).provider.getPackageName().equals(
                "com.digiflip.scada")
                && appWidgetInfos.get(j).provider.getClassName().equals(
                        "com.digiflip.service.AppWidget")) {
            // Get the full info of the required widget
            newAppWidgetProviderInfo = appWidgetInfos.get(j);
            break;
        }
    }
    mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, cn);
    AppWidgetHostView hostView = mAppWidgetHost.createView(this,
            appWidgetId, newAppWidgetProviderInfo);
    hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);
    mainlayout.addView(hostView);
}

/**
 * Handles the menu.
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.i(TAG,
            "Menu selected: " + item.getTitle() + " / " + item.getItemId()
                    + " / " + R.id.addWidget);
    switch (item.getItemId()) {
    case R.id.addWidget:
        my();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * Creates the menu with options to add and remove widgets.
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.widget_menu, menu);
    return true;
}
 }

above code is working if I add appwidget to activity. but I want to add appwidget to homescreen.

actually I don't understand how to take view or reference of homescreen to add view by appwidgethostview.

please help me regarding this.. thanx in advance.

Shashank Gupta
  • 165
  • 2
  • 16
  • Follow this link for create app widget in home screen. https://github.com/ChiragSavsani/FlashLightWidget – Chirag Savsani Nov 03 '15 at 06:13
  • Did that code worked? – Chirag Savsani Nov 03 '15 at 07:14
  • hello Chirag thanx for help but my task is not solved because in this example, appWidget is added to homescreen manually but I want to add appwidget to homescreen programatically not manually pick appwidget and drop on homescreen...... – Shashank Gupta Nov 03 '15 at 10:43
  • Then Refer [This](http://stackoverflow.com/questions/16100926/how-to-add-a-widget-to-the-android-home-screen-from-my-app) or [This](http://stackoverflow.com/questions/22829647/programmatically-add-the-widget-to-home-screen-in-android) may be that links can help you. – Chirag Savsani Nov 03 '15 at 10:47
  • hello chirag I also tried these link. 2nd link is not related to me this link only related to add app shorcut to homescreen not related to appwidget. and your 1st link is tried but this link does not discribe to add appwidget to homescreen, it only discribe to add appwidget to activity by appwidgethostview which is already done by me.. – Shashank Gupta Nov 03 '15 at 11:20

1 Answers1

0

In Android O, its possible to set app widget programmatically.

AppWidgetManager mAppWidgetManager =
    context.getSystemService(AppWidgetManager.class);

AppWidgetProviderInfo myWidgetProviderInfo = new AppWidgetProviderInfo();
ComponentName myProvider = myWidgetProviderInfo.provider;

if (mAppWidgetManager.isRequestPinAppWidgetSupported()) {
  // Create the PendingIntent object only if your app needs to be notified
  // that the user allowed the widget to be pinned. Note that, if the pinning
  // operation fails, your app isn't notified.
  Intent pinnedWidgetCallbackIntent = new Intent( ... );

  // Configure the intent so that your app's broadcast receiver gets
  // the callback successfully. This callback receives the ID of the
  // newly-pinned widget (EXTRA_APPWIDGET_ID).
  PendingIntent successCallback = PendingIntent.createBroadcast(context, 0,
          pinnedWidgetCallbackIntent);

  mAppWidgetManager.requestPinAppWidget(myProvider, null,
           successCallback.getIntentSender());
}

Also check out Google official documentation

HeyAlex
  • 1,666
  • 1
  • 13
  • 31