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:Main.java

public static final boolean isKeyguardWidget(int appWidgetId, Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context.getApplicationContext());

        return appWidgetManager.getAppWidgetOptions(appWidgetId).getInt(
                AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
                -1) == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD;
    }/*from  ww  w  .j av a2 s.  c o  m*/

    return false;
}

From source file:eu.power_switch.widget.provider.ReceiverWidgetProvider.java

/**
 * Forces an Update of all Receiver Widgets
 *
 * @param context any suitable context/* www  .j  a va2 s .  c  o m*/
 */
public static void forceWidgetUpdate(Context context) {
    // update receiver widgets
    Intent intent = new Intent(context, ReceiverWidgetProvider.class);
    intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    int ids[] = AppWidgetManager.getInstance(context.getApplicationContext())
            .getAppWidgetIds(new ComponentName(context.getApplicationContext(), ReceiverWidgetProvider.class));
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
    context.sendBroadcast(intent);
}

From source file:me.sandrin.xkcdwidget.XKCDAppWidgetProvider.java

private void update(Context context) {
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget_layout);
    ComponentName watchWidget = new ComponentName(context, XKCDAppWidgetProvider.class);

    title = context.getResources().getString(R.string.error_title);
    image = null;/*  w w w  .ja v  a  2  s.  c  o m*/
    altText = context.getResources().getString(R.string.error_text);
    updateComicInfo();
    updateRemoteViews(context, remoteViews);

    appWidgetManager.updateAppWidget(watchWidget, remoteViews);
}

From source file:com.fbartnitzek.tasteemall.widget.StatsWidgetIntentService.java

@Override
protected void onHandleIntent(Intent intent) {

    //        Log.v(LOG_TAG, "onHandleIntent, hashCode=" + this.hashCode() + ", " + "intent = [" + intent + "]");

    // get all widget ids
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, StatsWidgetProvider.class));

    // query all entities
    int numLocations = queryAndGetCount(DatabaseContract.LocationEntry.CONTENT_URI,
            QueryColumns.Widget.LocationQuery.COLUMNS);
    int numProducers = queryAndGetCount(DatabaseContract.ProducerEntry.CONTENT_URI,
            QueryColumns.Widget.ProviderQuery.COLUMNS);
    int numDrinks = queryAndGetCount(DatabaseContract.DrinkEntry.CONTENT_URI,
            QueryColumns.Widget.DrinkQuery.COLUMNS);
    int numUsers = queryAndGetCount(DatabaseContract.UserEntry.CONTENT_URI,
            QueryColumns.Widget.UserQuery.COLUMNS);
    int numReviews = queryAndGetCount(DatabaseContract.ReviewEntry.CONTENT_URI,
            QueryColumns.Widget.ReviewQuery.COLUMNS);

    // TODO: results are getting "cached" or something like that ...
    // maybe that helps: http://stackoverflow.com/questions/9497270/widget-with-content-provider-impossible-to-use-readpermission
    Log.v(LOG_TAG,//from w  w  w  .  j  a v  a2  s  . c  o  m
            "onHandleIntent, producer=" + numProducers + ", drinks=" + numDrinks + ", reviews=" + numReviews);

    for (int appWidgetId : appWidgetIds) {
        // dynamically adapt widget width ... later

        RemoteViews views = new RemoteViews(getPackageName(), R.layout.info_widget);

        // fill stats
        views.setTextViewText(R.id.stats_locations,
                getString(R.string.widget_statistics_locations, numLocations));

        views.setTextViewText(R.id.stats_producers,
                getString(R.string.widget_statistics_producers, numProducers));

        views.setTextViewText(R.id.stats_drinks, getString(R.string.widget_statistics_drinks, numDrinks));

        views.setTextViewText(R.id.stats_users, getString(R.string.widget_statistics_users, numUsers));

        views.setTextViewText(R.id.stats_reviews, getString(R.string.widget_statistics_reviews, numReviews));

        // seems to be impossible to get contentDescription for whole widget...
        //            views.setContentDescription(R.id.widget_layout,
        //                    getString(R.string.a11y_widget_statistics_all, numProducers, numDrinks, numReviews));

        views.setContentDescription(R.id.stats_reviews,
                getString(R.string.a11y_widget_statistics_all, numProducers, numDrinks, numReviews));

        // set on click listener for add and search on every update (kind of useless...)

        // add button - create backStack for add
        Intent addIntent = new Intent(this, AddReviewActivity.class);
        PendingIntent addPendingIntent = TaskStackBuilder.create(this).addNextIntentWithParentStack(addIntent)
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.widget_add_button, addPendingIntent);

        // search button
        PendingIntent searchPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
        views.setOnClickPendingIntent(R.id.widget_search_button, searchPendingIntent);

        // update each StatsWidget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

From source file:com.chainsaw.clearweather.OpenWeatherAPI.java

public OpenWeatherAPI(final Context context, final int widgetId) {
    final RemoteViews remote = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
    final AppWidgetManager manager = AppWidgetManager.getInstance(context);

    asyncLoader = new BackgroundFetch(context) {
        @Override/*w w  w  . j av  a  2 s . c o  m*/
        protected void onPostExecute(WeatherData result) {
            remote.setViewVisibility(R.id.loading, View.INVISIBLE);
            if (OpenWeatherAPI.this.listener != null)
                OpenWeatherAPI.this.listener.onDataReady(result);

        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            remote.setViewVisibility(R.id.temp, View.INVISIBLE);
            remote.setViewVisibility(R.id.tempUnit, View.INVISIBLE);
            remote.setViewVisibility(R.id.humidity, View.INVISIBLE);
            remote.setViewVisibility(R.id.humidityUnit, View.INVISIBLE);
            remote.setViewVisibility(R.id.location, View.INVISIBLE);
            remote.setViewVisibility(R.id.weather, View.INVISIBLE);
            remote.setViewVisibility(R.id.timestamp, View.INVISIBLE);
            remote.setViewVisibility(R.id.loading, View.VISIBLE);
            remote.setProgressBar(R.id.loading, 10, 5, true);
            manager.updateAppWidget(widgetId, remote);

            super.onProgressUpdate(values);

        }
    };
}

From source file:com.tortel.deploytrack.WidgetPickerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Check for light theme
    Prefs.load(this);
    if (Prefs.useLightTheme()) {
        setTheme(R.style.Theme_DeployThemeLight);
    }/* www  . jav a  2s. c o m*/

    setContentView(R.layout.activity_widget_config);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
    }
    mResultIntent = new Intent();
    //Set it to cancelled until explicitly told to save
    setResult(RESULT_CANCELED, mResultIntent);

    mWidgetManager = AppWidgetManager.getInstance(this);

    mAdapter = new DeploymentFragmentAdapter(this, getSupportFragmentManager());

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(mAdapter);

    SmartTabLayout indicator = (SmartTabLayout) findViewById(R.id.indicator);
    indicator.setViewPager(pager);
    indicator.setOnPageChangeListener(new PageChangeListener());

    pager.setCurrentItem(mCurrentPosition);

    Log.d("WidgetPicker started with mWidgetId " + mWidgetId);
}

From source file:de.micmun.android.workdaystarget.DaysLeftService.java

/**
 * Updates the days to target./*from w ww.j a  va 2 s.c  om*/
 */
private void updateDays() {
    AppWidgetManager appManager = AppWidgetManager.getInstance(this);
    ComponentName cName = new ComponentName(getApplicationContext(), DaysLeftProvider.class);
    int[] appIds = appManager.getAppWidgetIds(cName);

    DayCalculator dayCalc = new DayCalculator();
    if (!isOnline()) {
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            Log.e(TAG, "Interrupted: " + e.getLocalizedMessage());
        }
    }

    for (int appId : appIds) {
        PrefManager pm = new PrefManager(this, appId);
        Calendar target = pm.getTarget();
        boolean[] chkDays = pm.getCheckedDays();
        int days = pm.getLastDiff();

        if (isOnline()) {
            try {
                days = dayCalc.getDaysLeft(target.getTime(), chkDays);
                Map<String, Object> saveMap = new HashMap<String, Object>();
                Long diff = Long.valueOf(days);
                saveMap.put(PrefManager.KEY_DIFF, diff);
                pm.save(saveMap);
            } catch (JSONException e) {
                Log.e(TAG, "ERROR holidays: " + e.getLocalizedMessage());
            }
        } else {
            Log.e(TAG, "No internet connection!");
        }
        RemoteViews rv = new RemoteViews(this.getPackageName(), R.layout.appwidget_layout);
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
        String targetStr = df.format(target.getTime());
        rv.setTextViewText(R.id.target, targetStr);
        String dayStr = String.format(Locale.getDefault(), "%d %s", days,
                getResources().getString(R.string.unit));
        rv.setTextViewText(R.id.dayCount, dayStr);

        // put widget id into intent
        Intent configIntent = new Intent(this, ConfigActivity.class);
        configIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        configIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appId);
        configIntent.setData(Uri.parse(configIntent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, configIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        rv.setOnClickPendingIntent(R.id.widgetLayout, pendIntent);

        // update widget
        appManager.updateAppWidget(appId, rv);
    }
}

From source file:com.android.settings.applications.ClearDefaultsPreference.java

public ClearDefaultsPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);

    setLayoutResource(R.layout.app_preferred_settings);

    mAppWidgetManager = AppWidgetManager.getInstance(context);
    mPm = context.getPackageManager();/*from ww w  .j  ava  2  s .c om*/
    IBinder b = ServiceManager.getService(Context.USB_SERVICE);
    mUsbManager = IUsbManager.Stub.asInterface(b);
}

From source file:com.udacity.stockhawk.ui.widget.StockWidget.java

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    if (QuoteSyncJob.ACTION_DATA_UPDATED.equals(intent.getAction())) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

        appWidgetManager.notifyAppWidgetViewDataChanged(
                appWidgetManager.getAppWidgetIds(new ComponentName(context, getClass())), R.id.lv_widget_stock);
    }/*from ww w  .  j a  v a2 s .c o m*/
}

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

public void onReceive(Context ctxt, Intent intent) {
    String action = intent.getAction();
    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
        // Remove widget alarm
        int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        PendingIntent pi = PendingIntent.getService(ctxt, widgetId, getIntent(ctxt, widgetId), 0);
        AlarmManager am = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pi);// w w w .j a  v  a2s .c  o m

        // remove preference
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctxt);
        Editor edit = prefs.edit();
        edit.remove(Main.PREF_API_URL_WIDGET + widgetId);
        edit.remove(Main.PREF_INIT_WIDGET + widgetId);
        edit.remove(Main.PREF_LAST_WIDGET + widgetId);
        edit.remove(Main.PREF_FORCE_WIDGET + widgetId);
        edit.commit();

        // Log.i(Main.TAG, "Remove widget alarm for id=" + widgetId);
    } else if (intent.hasExtra(WIDGET_IDS) && AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
        int[] ids = intent.getExtras().getIntArray(WIDGET_IDS);
        onUpdate(ctxt, AppWidgetManager.getInstance(ctxt), ids);
    } else
        super.onReceive(ctxt, intent);
}