Example usage for android.appwidget AppWidgetManager getInstance

List of usage examples for android.appwidget AppWidgetManager getInstance

Introduction

In this page you can find the example usage for android.appwidget AppWidgetManager getInstance.

Prototype

public static AppWidgetManager getInstance(Context context) 

Source Link

Document

Get the AppWidgetManager instance to use for the supplied android.content.Context Context object.

Usage

From source file:eu.power_switch.widget.activity.ConfigureReceiverWidgetActivity.java

private void saveCurrentConfiguration() {
    try {//  ww  w  . j  a v a2s .c  o  m
        // First, get the App Widget ID from the Intent that launched the Activity:
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
            int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            // Perform your App Widget configuration:
            Apartment selectedApartment = getSelectedApartment();
            Room selectedRoom = selectedApartment.getRoom(spinnerRoom.getSelectedItem().toString());
            Receiver selectedReceiver = selectedRoom.getReceiver(spinnerReceiver.getSelectedItem().toString());

            // save new widget data to database
            ReceiverWidget receiverWidget = new ReceiverWidget(appWidgetId, selectedRoom.getId(),
                    selectedReceiver.getId());
            DatabaseHandler.addReceiverWidget(receiverWidget);
            // When the configuration is complete, get an instance of
            // the AppWidgetManager by calling getInstance(Context):
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(ConfigureReceiverWidgetActivity.this);
            // Update the App Widget with a RemoteViews layout by
            // calling updateAppWidget(int, RemoteViews):
            RemoteViews remoteViews = new RemoteViews(getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                    R.layout.widget_receiver);

            LinkedList<Button> buttons = selectedReceiver.getButtons();

            remoteViews.setTextViewText(R.id.textView_receiver_widget_name, selectedApartment.getName() + ": "
                    + selectedRoom.getName() + ": " + selectedReceiver.getName());

            int buttonOffset = 0;
            for (Button button : buttons) {
                // set button action
                RemoteViews buttonView = new RemoteViews(
                        getString(eu.power_switch.shared.R.string.PACKAGE_NAME),
                        R.layout.widget_receiver_button_layout);
                SpannableString s = new SpannableString(button.getName());
                s.setSpan(new StyleSpan(Typeface.BOLD), 0, button.getName().length(), 0);
                buttonView.setTextViewText(R.id.button_widget_universal, s);

                if (SmartphonePreferencesHandler.getHighlightLastActivatedButton()
                        && selectedReceiver.getLastActivatedButtonId().equals(button.getId())) {
                    buttonView.setTextColor(R.id.button_widget_universal,
                            ContextCompat.getColor(getApplicationContext(), R.color.color_light_blue_a700));
                }

                PendingIntent pendingIntent = WidgetIntentReceiver.buildReceiverWidgetActionPendingIntent(
                        getApplicationContext(), selectedApartment, selectedRoom, selectedReceiver, button,
                        appWidgetId * 15 + buttonOffset);

                buttonView.setOnClickPendingIntent(R.id.button_widget_universal, pendingIntent);

                remoteViews.addView(R.id.linearlayout_receiver_widget, buttonView);
                buttonOffset++;
            }

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

            // Finally, create the return Intent, set it with the
            // Activity result, and finish the Activity:
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    } catch (Exception e) {
        StatusMessageHandler.showErrorMessage(this, e);
    }
}

From source file:com.android.launcher3.QsbContainerView.java

/**
 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
 * provided by the same package which is set to be global search activity.
 * If widgetCategory is not supported, or no such widget is found, returns the first widget
 * provided by the package.//from w w w.  j a  va 2s. com
 */
public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
    SearchManager searchManager = (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
    ComponentName searchComponent = searchManager.getGlobalSearchActivity();
    if (searchComponent == null)
        return null;
    String providerPkg = searchComponent.getPackageName();

    AppWidgetProviderInfo defaultWidgetForSearchPackage = null;

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
        if (info.provider.getPackageName().equals(providerPkg) && info.configure == null) {
            if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
                return info;
            } else if (defaultWidgetForSearchPackage == null) {
                defaultWidgetForSearchPackage = info;
            }
        }
    }
    return defaultWidgetForSearchPackage;
}

From source file:net.olejon.mdapp.MyTools.java

public void updateWidget() {
    ComponentName componentName = new ComponentName(mContext, Widget.class);

    int[] appWidgetIds = AppWidgetManager.getInstance(mContext).getAppWidgetIds(componentName);

    Intent intent = new Intent(mContext, Widget.class);
    intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

    mContext.sendBroadcast(intent);/*from   w  w w  .j a  va 2s .  co  m*/
}

From source file:fr.shywim.antoinedaniel.ui.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case SETTINGS_REQUEST_CODE:
        AppWidgetManager man = AppWidgetManager.getInstance(this);
        if (man != null) {
            int[] ids = man.getAppWidgetIds(new ComponentName(mAppContext, HomeScreenWidgetProvider.class));
            Intent updateIntent = new Intent();
            updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            updateIntent.putExtra(HomeScreenWidgetProvider.WIDGET_IDS_KEY, ids);
            this.sendBroadcast(updateIntent);
        }//from w w w.j  av a2  s.c o  m

        if (resultCode == RESULT_CONNECT_GOOGLE_CODE) {
            mTaskFragment.connectPlayServices(findViewById(VIEW_ID_POPUPS));
        }
        break;

    case PURCHASE_REQUEST_CODE:
        if (resultCode == RESULT_OK) {
            String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
            try {
                JSONObject jo = new JSONObject(purchaseData);
                String sku = jo.getString("productId");
                if (sku.equals(utils.SKU_DONATE)) {
                    PrefUtils.setUserDonated(this, true);
                    Toast.makeText(this, R.string.toast_purchase_thanks, Toast.LENGTH_LONG).show();
                    mAdView.destroy();
                    LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
                    adLayout.setVisibility(View.GONE);
                }
            } catch (JSONException e) {
                Toast.makeText(mContext, R.string.error, Toast.LENGTH_SHORT).show();
            }
        }
        break;

    case BlindGameActivity.REQUEST_CODE:
        /*if (resultCode == RESULT_OK){
           selectItem(DrawerPosition.GAMES, data.getExtras());
        } else selectItem(DrawerPosition.GAMES, null);*/
        break;

    case 1001:
        if (resultCode == RESULT_OK) {
            mTaskFragment.connectPlayServices(findViewById(VIEW_ID_POPUPS));
        } else {
            PrefUtils.setRefusedGoogle(this, true);
        }
        break;
    }
}

From source file:org.gnucash.android.ui.homescreen.WidgetConfigurationActivity.java

/**
 * Updates the widget with id <code>appWidgetId</code> with information from the 
 * account with record ID <code>accountId</code>
  * If the account has been deleted, then a notice is posted in the widget
 * @param appWidgetId ID of the widget to be updated
 *//*from  ww w .j a  v  a  2  s  . co m*/
public static void updateWidget(final Context context, int appWidgetId) {
    Log.i("WidgetConfiguration", "Updating widget: " + appWidgetId);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

    loadOldPreferences(context, appWidgetId);

    SharedPreferences preferences = context.getSharedPreferences("widget:" + appWidgetId, MODE_PRIVATE);
    String bookUID = preferences.getString(UxArgument.BOOK_UID, null);
    String accountUID = preferences.getString(UxArgument.SELECTED_ACCOUNT_UID, null);
    boolean hideAccountBalance = preferences.getBoolean(UxArgument.HIDE_ACCOUNT_BALANCE_IN_WIDGET, false);

    if (bookUID == null || accountUID == null) {
        return;
    }

    AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(BookDbHelper.getDatabase(bookUID));

    final Account account;
    try {
        account = accountsDbAdapter.getRecord(accountUID);
    } catch (IllegalArgumentException e) {
        Log.i("WidgetConfiguration", "Account not found, resetting widget " + appWidgetId);
        //if account has been deleted, let the user know
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_4x1);
        views.setTextViewText(R.id.account_name, context.getString(R.string.toast_account_deleted));
        views.setTextViewText(R.id.transactions_summary, "");
        //set it to simply open the app
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, AccountsActivity.class), 0);
        views.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);
        views.setOnClickPendingIntent(R.id.btn_new_transaction, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, views);
        Editor editor = PreferenceActivity.getActiveBookSharedPreferences().edit(); //PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.remove(UxArgument.SELECTED_ACCOUNT_UID + appWidgetId);
        editor.apply();
        return;
    }

    final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_4x1);
    views.setTextViewText(R.id.account_name, account.getName());

    Money accountBalance = accountsDbAdapter.getAccountBalance(accountUID, -1, System.currentTimeMillis());

    if (hideAccountBalance) {
        views.setViewVisibility(R.id.transactions_summary, View.GONE);
    } else {
        views.setTextViewText(R.id.transactions_summary, accountBalance.formattedString(Locale.getDefault()));
        int color = accountBalance.isNegative() ? R.color.debit_red : R.color.credit_green;
        views.setTextColor(R.id.transactions_summary, context.getResources().getColor(color));
    }

    Intent accountViewIntent = new Intent(context, TransactionsActivity.class);
    accountViewIntent.setAction(Intent.ACTION_VIEW);
    accountViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    accountViewIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
    accountViewIntent.putExtra(UxArgument.BOOK_UID, bookUID);
    PendingIntent accountPendingIntent = PendingIntent.getActivity(context, appWidgetId, accountViewIntent, 0);
    views.setOnClickPendingIntent(R.id.widget_layout, accountPendingIntent);

    if (accountsDbAdapter.isPlaceholderAccount(accountUID)) {
        views.setOnClickPendingIntent(R.id.btn_view_account, accountPendingIntent);
        views.setViewVisibility(R.id.btn_new_transaction, View.GONE);
    } else {
        Intent newTransactionIntent = new Intent(context, FormActivity.class);
        newTransactionIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
        newTransactionIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newTransactionIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name());
        newTransactionIntent.putExtra(UxArgument.BOOK_UID, bookUID);
        newTransactionIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, newTransactionIntent, 0);
        views.setOnClickPendingIntent(R.id.btn_new_transaction, pendingIntent);
        views.setViewVisibility(R.id.btn_view_account, View.GONE);
    }

    appWidgetManager.updateAppWidget(appWidgetId, views);
}

From source file:de.hackerspacebremen.fragments.StatusFragment.java

private void updateAppWidget(SpaceData data) {
    SharedPreferences dataPersistence = getActivity().getSharedPreferences(Constants.SPACE_DATA_PERSISTENCE,
            Context.MODE_PRIVATE);
    Editor editor = dataPersistence.edit();
    editor.putBoolean(Constants.SPACE_OPEN_DATA_KEY, data.isSpaceOpen());
    editor.commit();//from w w w. j a  v  a2 s .c o  m

    RemoteViews remoteViews = new RemoteViews(getActivity().getPackageName(), R.layout.appwidget);
    remoteViews.setViewVisibility(R.id.indicatorImage, View.VISIBLE);
    remoteViews.setViewVisibility(R.id.errorText, View.GONE);

    if (data.isSpaceOpen()) {
        remoteViews.setImageViewResource(R.id.indicatorImage, R.drawable.banner);
    } else {
        remoteViews.setImageViewResource(R.id.indicatorImage, R.drawable.banner_blur);
    }

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getActivity());
    ComponentName componentName = new ComponentName(getActivity(), HackerspaceWidgetProvider.class);
    appWidgetManager.updateAppWidget(componentName, remoteViews);
}

From source file:ch.fixme.status.Widget.java

public static void UpdateAllWidgets(final Context ctxt) {
    AppWidgetManager man = AppWidgetManager.getInstance(ctxt);
    int[] ids = man.getAppWidgetIds(new ComponentName(ctxt, Widget.class));
    Intent ui = new Intent();
    ui.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    ui.putExtra(Widget.WIDGET_IDS, ids);
    ui.putExtra(Widget.WIDGET_FORCE, true);
    ctxt.sendBroadcast(ui);/*from   w w w  .java2  s  . c  o  m*/
}

From source file:com.farmerbb.taskbar.service.DashboardService.java

@SuppressLint("RtlHardcoded")
private void drawDashboard() {
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            PixelFormat.TRANSLUCENT);/*from w w w  .j a v a 2 s .  co  m*/

    // Initialize views
    layout = new LinearLayout(this);
    layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    layout.setVisibility(View.GONE);
    layout.setAlpha(0);

    SharedPreferences pref = U.getSharedPreferences(this);
    int width = pref.getInt("dashboard_width",
            getApplicationContext().getResources().getInteger(R.integer.dashboard_width));
    int height = pref.getInt("dashboard_height",
            getApplicationContext().getResources().getInteger(R.integer.dashboard_height));

    boolean isPortrait = getApplicationContext().getResources()
            .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    boolean isLandscape = getApplicationContext().getResources()
            .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;

    if (isPortrait) {
        columns = height;
        rows = width;
    }

    if (isLandscape) {
        columns = width;
        rows = height;
    }

    maxSize = columns * rows;

    int backgroundTint = U.getBackgroundTint(this);
    int accentColor = U.getAccentColor(this);
    int accentColorAlt = accentColor;
    accentColorAlt = ColorUtils.setAlphaComponent(accentColorAlt, Color.alpha(accentColorAlt) / 2);

    int cellCount = 0;

    for (int i = 0; i < columns; i++) {
        LinearLayout layout2 = new LinearLayout(this);
        layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, 1));
        layout2.setOrientation(LinearLayout.VERTICAL);

        for (int j = 0; j < rows; j++) {
            DashboardCell cellLayout = (DashboardCell) View.inflate(this, R.layout.dashboard, null);
            cellLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT, 1));
            cellLayout.setBackgroundColor(backgroundTint);
            cellLayout.setOnClickListener(cellOcl);
            cellLayout.setOnHoverListener(cellOhl);

            TextView empty = (TextView) cellLayout.findViewById(R.id.empty);
            empty.setBackgroundColor(accentColorAlt);
            empty.setTextColor(accentColor);

            Bundle bundle = new Bundle();
            bundle.putInt("cellId", cellCount);

            cellLayout.setTag(bundle);
            cells.put(cellCount, cellLayout);
            cellCount++;

            layout2.addView(cellLayout);
        }

        layout.addView(layout2);
    }

    mAppWidgetManager = AppWidgetManager.getInstance(this);
    mAppWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
    mAppWidgetHost.startListening();

    for (int i = 0; i < maxSize; i++) {
        int appWidgetId = pref.getInt("dashboard_widget_" + Integer.toString(i), -1);
        if (appWidgetId != -1)
            addWidget(appWidgetId, i, false);
        else if (pref.getBoolean("dashboard_widget_" + Integer.toString(i) + "_placeholder", false))
            addPlaceholder(i);
    }

    mAppWidgetHost.stopListening();

    LocalBroadcastManager.getInstance(this).unregisterReceiver(toggleReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(addWidgetReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(removeWidgetReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(hideReceiver);

    LocalBroadcastManager.getInstance(this).registerReceiver(toggleReceiver,
            new IntentFilter("com.farmerbb.taskbar.TOGGLE_DASHBOARD"));
    LocalBroadcastManager.getInstance(this).registerReceiver(addWidgetReceiver,
            new IntentFilter("com.farmerbb.taskbar.ADD_WIDGET_COMPLETED"));
    LocalBroadcastManager.getInstance(this).registerReceiver(removeWidgetReceiver,
            new IntentFilter("com.farmerbb.taskbar.REMOVE_WIDGET_COMPLETED"));
    LocalBroadcastManager.getInstance(this).registerReceiver(hideReceiver,
            new IntentFilter("com.farmerbb.taskbar.HIDE_DASHBOARD"));

    windowManager.addView(layout, params);

    new Handler().postDelayed(() -> {
        int paddingSize = getResources().getDimensionPixelSize(R.dimen.icon_size);

        switch (U.getTaskbarPosition(DashboardService.this)) {
        case "top_vertical_left":
        case "bottom_vertical_left":
            layout.setPadding(paddingSize, 0, 0, 0);
            break;
        case "top_left":
        case "top_right":
            layout.setPadding(0, paddingSize, 0, 0);
            break;
        case "top_vertical_right":
        case "bottom_vertical_right":
            layout.setPadding(0, 0, paddingSize, 0);
            break;
        case "bottom_left":
        case "bottom_right":
            layout.setPadding(0, 0, 0, paddingSize);
            break;
        }
    }, 100);
}

From source file:de.ub0r.android.callmeter.ui.prefs.PreferencesPlain.java

/** Load widget list. */
@SuppressWarnings("deprecation")
private void loadWidgets() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Preference p = findPreference("container");
    if (p != null && p instanceof PreferenceScreen) {
        PreferenceScreen ps = (PreferenceScreen) p;
        ps.removeAll();//  www. j  ava2s . c om
        int[] ids = AppWidgetManager.getInstance(this)
                .getAppWidgetIds(new ComponentName(this, StatsAppWidgetProvider.class));
        boolean added = false;
        if (ids != null && ids.length > 0) {
            for (int id : ids) {
                if (prefs.getLong(StatsAppWidgetProvider.WIDGET_PLANID + id, -1) <= 0) {
                    continue;
                }
                added = true;
                p = new Preference(this);
                p.setTitle(getString(R.string.widget_) + " #" + id);
                final int fid = id;
                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(final Preference preference) {
                        Intent i = new Intent(PreferencesPlain.this, StatsAppWidgetConfigure.class);
                        i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, fid);
                        PreferencesPlain.this.startActivity(i);
                        return true;
                    }
                });
                ps.addPreference(p);
            }
        }
        ids = AppWidgetManager.getInstance(this)
                .getAppWidgetIds(new ComponentName(this, LogsAppWidgetProvider.class));
        if (ids != null && ids.length > 0) {
            for (int id : ids) {
                if (prefs.getLong(LogsAppWidgetProvider.WIDGET_PLANID + id, -1) <= 0) {
                    continue;
                }
                added = true;
                p = new Preference(this);
                p.setTitle(getString(R.string.widget_) + " #" + id);
                final int fid = id;
                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(final Preference preference) {
                        Intent i = new Intent(PreferencesPlain.this, LogsAppWidgetConfigure.class);
                        i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, fid);
                        PreferencesPlain.this.startActivity(i);
                        return true;
                    }
                });
                ps.addPreference(p);
            }
        }
        if (!added) {
            p = new Preference(this);
            p.setTitle(R.string.widgets_no_widgets_);
            p.setSummary(R.string.widgets_no_widgets_hint);
            ps.addPreference(p);
        }
    }
}

From source file:de.domjos.schooltools.helper.Helper.java

public static void sendBroadCast(Context context, Class cls) {
    Intent intent = new Intent(context, cls);
    intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    int[] ids = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, cls));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
    context.sendBroadcast(intent);/*from  ww  w .  j  a  v a 2  s  .  co m*/
}