如何通过单击活动中的按钮将appwidget添加到主屏幕

时间:2015-11-03 05:58:48

标签: android android-appwidget appwidgetprovider

我在Activty中创建一个按钮,然后单击按钮我想在Android中以编程方式将Appwidget添加到Homescreen。

实际上我使用appwidgethost类将appwidget添加到主屏幕,但appwidget被添加到活动而不是主屏幕。我的代码在下面

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;
}
 }
如果我将appwidget添加到活动,则上面的代码正常工作。但我想将appwidget添加到主屏幕。

实际上我不明白如何通过appwidgethostview来查看或引用主屏幕来添加视图。

请帮我解决这个问题.. 提前完成。

1 个答案:

答案 0 :(得分:0)

在Android O中,可以通过编程方式设置应用小部件。

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());
}

另请查看Google官方documentation