Java Code Examples for android.appwidget.AppWidgetManager#getInstance()

The following examples show how to use android.appwidget.AppWidgetManager#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SettingsActivity.java    From WalletCordova with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void onStop() {
    super.onStop();
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);

    final ComponentName providerName = new ComponentName(this, WalletBalanceWidgetProvider.class);

    try
    {
        final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(providerName);

        if (appWidgetIds.length > 0)
        {
            WalletBalanceWidgetProvider.runAsyncTask(this, appWidgetManager, appWidgetIds);
        }
    }
    catch (final RuntimeException x)
    {
    }
}
 
Example 2
Source File: ShotWidgetService.java    From droidddle with Apache License 2.0 6 votes vote down vote up
@Override
public void onDataSetChanged() {
    if (!Utils.hasInternet(mContext)) {
        Toast.makeText(mContext, R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
    try {
        ShotAppWidgetProvider.setupWidget(mContext, appWidgetManager, mAppWidgetId, true);
        List<Shot> shots = ApiFactory.getService(mContext).getShotsSync(null, "recent", null, 1);
        updateShots(shots);
    } catch (Exception e) {
        e.printStackTrace();
    }
    ShotAppWidgetProvider.setupWidget(mContext, appWidgetManager, mAppWidgetId, false);
}
 
Example 3
Source File: WidgetActivity.java    From Torch with GNU General Public License v3.0 6 votes vote down vote up
public void addWidget() {
    Editor mEditor = mPreferences.edit();
    mEditor.putBoolean("widget_sos" + mAppWidgetId, mPreferences.getBoolean(KEY_WIDGET_SOS, false));
    mEditor.commit();

    // Initialize widget view for first update
    Context mContext = getApplicationContext();
    RemoteViews mViews = new RemoteViews(mContext.getPackageName(), R.layout.widget);
    mViews.setImageViewResource(R.id.widget, R.drawable.widget_off);
    Intent mLaunchIntent = new Intent();
    mLaunchIntent.setClass(mContext, MainActivity.class);
    mLaunchIntent.addCategory(Intent.CATEGORY_ALTERNATIVE);
    mLaunchIntent.setData(Uri.parse("custom:" + mAppWidgetId + "/0"));
    PendingIntent mPendingIntent = PendingIntent.getBroadcast(mContext, 0, mLaunchIntent, 0);
    mViews.setOnClickPendingIntent(R.id.button, mPendingIntent);

    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
    appWidgetManager.updateAppWidget(mAppWidgetId, mViews);

    Intent mResultValue = new Intent();
    mResultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
    setResult(RESULT_OK, mResultValue);

    // Close the activity
    finish();
}
 
Example 4
Source File: NoteListWidget.java    From nextcloud-notes with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    AppWidgetManager awm = AppWidgetManager.getInstance(context);

    if (intent.getAction() != null) {
        if (intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                if (intent.getExtras() != null) {
                    updateAppWidget(context, awm, new int[]{intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1)});
                } else {
                    Log.w(TAG, "intent.getExtras() is null");
                }
            } else {
                updateAppWidget(context, awm, awm.getAppWidgetIds(new ComponentName(context, NoteListWidget.class)));
            }
        }
    } else {
        Log.w(TAG, "intent.getAction() is null");
    }
}
 
Example 5
Source File: OverclockingWidgetView.java    From rpicheck with MIT License 6 votes vote down vote up
public static RemoteViews initDefaultView(Context context, int appWidgetId, RaspberryDeviceBean deviceBean, boolean showTemp, boolean showArm, boolean showLoad, boolean showMemory) {
    LOGGER.debug("Initiating default view for Widget[ID={}].", appWidgetId);
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.overclocking_widget);
    views.setOnClickPendingIntent(R.id.buttonRefresh, getSelfPendingIntent(context, appWidgetId, ACTION_WIDGET_UPDATE_ONE_MANUAL));
    PendingIntent activityIntent = getActivityIntent(context);
    views.setOnClickPendingIntent(R.id.linLayoutName, activityIntent);
    views.setOnClickPendingIntent(R.id.linLayoutTemp, activityIntent);
    views.setOnClickPendingIntent(R.id.linLayoutArm, activityIntent);
    views.setOnClickPendingIntent(R.id.linLayoutLoad, activityIntent);
    views.setOnClickPendingIntent(R.id.linLayoutMem, activityIntent);
    views.setTextViewText(R.id.textDeviceValue, deviceBean.getName());
    views.setTextViewText(R.id.textDeviceUserHost, String.format("%s@%s", deviceBean.getUser(), deviceBean.getHost()));
    views.setViewVisibility(R.id.linLayoutTemp, showTemp ? View.VISIBLE : View.GONE);
    views.setViewVisibility(R.id.linLayoutArm, showArm ? View.VISIBLE : View.GONE);
    views.setViewVisibility(R.id.linLayoutLoad, showLoad ? View.VISIBLE : View.GONE);
    views.setViewVisibility(R.id.linLayoutMem, showMemory ? View.VISIBLE : View.GONE);
    views.setProgressBar(R.id.progressBarArmValue, 100, 0, false);
    views.setProgressBar(R.id.progressBarLoad, 100, 0, false);
    views.setProgressBar(R.id.progressBarMemory, 100, 0, false);
    views.setProgressBar(R.id.progressBarTempValue, 100, 0, false);
    appWidgetManager.updateAppWidget(appWidgetId, views);
    return views;
}
 
Example 6
Source File: ShotAppWidgetConfigure.java    From droidddle with Apache License 2.0 5 votes vote down vote up
void update() {
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    RemoteViews views = new RemoteViews(getPackageName(), R.layout.shot_appwidget);
    appWidgetManager.updateAppWidget(mAppWidgetId, views);

    Intent resultValue = new Intent();
    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
    setResult(RESULT_OK, resultValue);
    finish();
}
 
Example 7
Source File: AbstractWidgetProvider.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    appendLog(context, TAG, "intent:", intent, ", widget:", getWidgetClass());
    Bundle extras = intent.getExtras();
    if (extras != null) {
        int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
        appendLog(context, TAG, "EXTRA_APPWIDGET_ID:" + appWidgetId);
    }

    super.onReceive(context, intent);
    AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);

    Integer widgetId = null;
    ComponentName widgetComponent = new ComponentName(context, getWidgetClass());

    if (intent.hasExtra("widgetId")) {
        widgetId = intent.getIntExtra("widgetId", 0);
        if (widgetId == 0) {
            widgetId = null;
        }
    }
    if (widgetId == null) {
        int[] widgetIds = widgetManager.getAppWidgetIds(widgetComponent);
        if (widgetIds.length == 0) {
            return;
        }
        for (int widgetIditer: widgetIds) {
            performActionOnReceiveForWidget(context, intent, widgetIditer);
        }
        return;
    }
    performActionOnReceiveForWidget(context, intent, widgetId);
}
 
Example 8
Source File: BaseAppWidget.java    From VinylMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
protected void pushUpdate(final Context context, final int[] appWidgetIds) {
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    if (appWidgetIds != null) {
        appWidgetManager.updateAppWidget(appWidgetIds, appWidgetView);
    } else {
        appWidgetManager.updateAppWidget(new ComponentName(context, getClass()), appWidgetView);
    }
}
 
Example 9
Source File: PrayerWidget.java    From MuslimMateAndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Receive broadcast for refresh
 *
 * @param context Application context
 * @param intent  Intent to do something
 */
@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    if (action.equals(PRAYER_CHANGE) || action.equals(Intent.ACTION_DATE_CHANGED)) {
        AppWidgetManager gm = AppWidgetManager.getInstance(context);
        int[] ids = gm.getAppWidgetIds(new ComponentName(context, PrayerWidget.class));
        this.onUpdate(context, gm, ids);
    } else {
        super.onReceive(context, intent);
    }
}
 
Example 10
Source File: PirateBoxWidget.java    From AndroidPirateBox with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	AppWidgetManager manager = AppWidgetManager.getInstance(context);
       int[] widgetIds = manager.getAppWidgetIds(new ComponentName(context, PirateBoxWidget.class));
  
       if(intent.getAction().equals(WIDGET_INTENT_CLICKED)) {
       	Intent serviceIntent = new Intent(context, PirateBoxService.class);
       	
       	boolean serverRunning = PirateBoxService.isRunning();
       	boolean startingUp = PirateBoxService.isStartingUp();
       	
       	// Only start if not running an not starting up
       	if(!serverRunning && !startingUp) {
       		showIntermediateImage(context);
       		context.startService(serviceIntent);
       	}
       	// Only stop service, if service is running
       	else if(serverRunning) {
       		showIntermediateImage(context);
       		context.stopService(serviceIntent);
       	}
       }
       else {
       	showWidget(context, manager, widgetIds, PirateBoxService.isRunning());
       }
       
       
}
 
Example 11
Source File: EarthquakeWidget.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent){
  super.onReceive(context, intent);

  if (NEW_QUAKE_BROADCAST.equals(intent.getAction())) {
    PendingResult pendingResult = goAsync();

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    ComponentName earthquakeWidget = new ComponentName(context, EarthquakeWidget.class);

    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(earthquakeWidget);

    updateAppWidgets(context, appWidgetManager, appWidgetIds, pendingResult);
  }
}
 
Example 12
Source File: AppWidgetSmall.java    From Orin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check against {@link AppWidgetManager} if there are any instances of this
 * widget.
 */
private boolean hasInstances(final Context context) {
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    final int[] mAppWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context,
            getClass()));
    return mAppWidgetIds.length > 0;
}
 
Example 13
Source File: WidgetUnified.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
static void init(Context context, int appWidgetId) {
    Log.i("Widget unified init=" + appWidgetId);

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    if (appWidgetManager == null) {
        Log.w("No app widget manager"); // Fairphone FP2
        return;
    }

    Intent intent = new Intent(context, WidgetUnified.class);
    intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[]{appWidgetId});
    context.sendBroadcast(intent);
}
 
Example 14
Source File: BaseAppWidget.java    From RetroMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
protected void pushUpdate(final Context context, final int[] appWidgetIds, final RemoteViews views) {
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    if (appWidgetIds != null) {
        appWidgetManager.updateAppWidget(appWidgetIds, views);
    } else {
        appWidgetManager.updateAppWidget(new ComponentName(context, getClass()), views);
    }
}
 
Example 15
Source File: BaseAppWidget.java    From Music-Player with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check against {@link AppWidgetManager} if there are any instances of this
 * widget.
 */
protected boolean hasInstances(final Context context) {
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    final int[] mAppWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context,
            getClass()));
    return mAppWidgetIds.length > 0;
}
 
Example 16
Source File: SearchWidgetProvider.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public SearchWidgetProviderDelegate(Context context) {
    mContext = context == null ? ContextUtils.getApplicationContext() : context;
    mManager = AppWidgetManager.getInstance(mContext);
}
 
Example 17
Source File: ProcessOwmUpdateCityListRequest.java    From privacy-friendly-weather with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Converts the response to JSON and updates the database so that the latest weather data are
 * displayed.
 *
 * @param response The response of the HTTP request.
 */
@Override
public void processSuccessScenario(String response) {
    IDataExtractor extractor = new OwmDataExtractor();
    try {
        JSONObject json = new JSONObject(response);
        JSONArray list = json.getJSONArray("list");
        for (int i = 0; i < list.length(); i++) {
            String currentItem = list.get(i).toString();
            CurrentWeatherData weatherData = extractor.extractCurrentWeatherData(currentItem);
            int cityId = extractor.extractCityID(currentItem);
            // Data were not well-formed, abort
            if (weatherData == null || cityId == Integer.MIN_VALUE) {
                final String ERROR_MSG = context.getResources().getString(R.string.convert_to_json_error);
                Toast.makeText(context, ERROR_MSG, Toast.LENGTH_LONG).show();
                return;
            }
            // Could retrieve all data, so proceed
            else {
                weatherData.setCity_id(cityId);

                CurrentWeatherData current = dbHelper.getCurrentWeatherByCityId(cityId);
                if(current != null && current.getCity_id() == cityId) {
                    dbHelper.updateCurrentWeather(weatherData);
                } else {
                    dbHelper.addCurrentWeather(weatherData);
                }
            }
        }

        //Update Widgets
        AppWidgetManager awm = AppWidgetManager.getInstance(context);

        int[] ids1 = awm.getAppWidgetIds(new ComponentName(context, WeatherWidget.class));
        int[] ids3 = awm.getAppWidgetIds(new ComponentName(context, WeatherWidgetThreeDayForecast.class));
        int[] ids5 = awm.getAppWidgetIds(new ComponentName(context, WeatherWidgetFiveDayForecast.class));

        Intent intent1 = new Intent(context, WeatherWidget.class);
        Intent intent3 = new Intent(context, WeatherWidgetThreeDayForecast.class);
        Intent intent5 = new Intent(context, WeatherWidgetFiveDayForecast.class);

        intent1.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent3.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent5.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);

        intent1.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids1);
        intent3.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids3);
        intent5.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids5);

        context.sendBroadcast(intent1);
        context.sendBroadcast(intent3);
        context.sendBroadcast(intent5);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    // TODO: Error Handling
}
 
Example 18
Source File: CourseAppWidgetProvider.java    From SmallGdufe-Android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 通知界面去更新UI,需要在修改UI后调用(不含列表数据)
 * @param context
 */
private void notifyUpdateUI(Context context) {
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    appWidgetManager.updateAppWidget(new ComponentName(context, CourseAppWidgetProvider.class), remoteViews);
}
 
Example 19
Source File: WeatherAppWidget.java    From LittleFreshWeather with Apache License 2.0 4 votes vote down vote up
@Override
public void renderData(WeatherEntity entity) {
    if (entity == null) {
        return;
    }

    mEntity = entity;

    ComponentName thisWidget = new ComponentName(mContext, WeatherAppWidget.class);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

    for (int i = 0; i < appWidgetIds.length; ++i) {
        int appWidgetId = appWidgetIds[i];
        RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.app_widget_layout);

        Intent intent = new Intent(mContext, SplashActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.ll_app_widget_root, pendingIntent);

        if (entity.getForecasts().size() > 0) {
            mDataDate = entity.getForecasts().get(0).getDate();
        }

        if (mDataDate != null && mDataDate.compareToIgnoreCase(StringUtil.getCurrentDateTime("yyyy-MM-dd")) != 0) {
            views.setTextColor(R.id.tv_app_widget_weather_desc, mContext.getApplicationContext().getResources().getColor(R.color.colorAirFour));
            views.setTextViewText(R.id.tv_app_widget_weather_desc, mContext.getApplicationContext().getString(R.string.data_out_of_date));
        } else {
            views.setTextColor(R.id.tv_app_widget_weather_desc, mContext.getApplicationContext().getResources().getColor(R.color.colorLightGray));
            views.setTextViewText(R.id.tv_app_widget_weather_desc, entity.getWeatherDescription());
        }
        views.setImageViewResource(R.id.iv_app_widget_weather_icon, getWeatherIconId(entity.getWeatherDescription()));
        views.setTextViewText(R.id.tv_app_widget_city_name, entity.getCityName());
        views.setTextViewText(R.id.tv_app_widget_temp, entity.getCurrentTemperature() + "℃");
        AirQulityRepresentation airQulityRepresentation = new AirQulityRepresentation();
        getAirQualityTypeAndColor(entity.getAirQulityIndex(), airQulityRepresentation);
        //views.setTextColor(R.id.tv_app_widget_air, airQulityRepresentation.getmAirQulityColorId());
        views.setTextViewText(R.id.tv_app_widget_air, airQulityRepresentation.getmAirQulityType());

        views.setTextViewText(R.id.tv_app_widget_time, StringUtil.getCurrentDateTime("HH:mm"));
        views.setTextViewText(R.id.tv_app_widget_dayofweek, StringUtil.getCurrentDateTime("EEEE"));
        views.setTextViewText(R.id.tv_app_widget_date, StringUtil.getCurrentDateTime("M月d日"));
        String[] dateAndTime = entity.getDataUpdateTime().split(" ");
        Date date = StringUtil.stringToDate("yyyy-MM-dd", dateAndTime[0]);
        views.setTextViewText(R.id.tv_app_widget_update_time, StringUtil.getFriendlyDateString(date, false) + " " + dateAndTime[1] + " 发布");

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    LogUtil.e(TAG, "renderData");
}
 
Example 20
Source File: AbstractWidgetProvider.java    From your-local-weather with GNU General Public License v3.0 4 votes vote down vote up
private void performActionOnReceiveForWidget(Context context, Intent intent, int widgetId) {
    AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
    LocationsDbHelper locationsDbHelper = LocationsDbHelper.getInstance(context);
    WidgetSettingsDbHelper widgetSettingsDbHelper = WidgetSettingsDbHelper.getInstance(context);
    Long locationId = widgetSettingsDbHelper.getParamLong(widgetId, "locationId");
    if (locationId == null) {
        currentLocation = locationsDbHelper.getLocationByOrderId(0);
        if (!currentLocation.isEnabled()) {
            currentLocation = locationsDbHelper.getLocationByOrderId(1);
        }
    } else {
        currentLocation = locationsDbHelper.getLocationById(locationId);
    }
    switch (intent.getAction()) {
        case "org.thosp.yourlocalweather.action.WEATHER_UPDATE_RESULT":
        case "android.appwidget.action.APPWIDGET_UPDATE":
            if (!servicesStarted) {
                onEnabled(context);
                servicesStarted = true;
            }
            onUpdate(context, widgetManager, new int[] {widgetId});
            break;
        case Intent.ACTION_LOCALE_CHANGED:
        case Constants.ACTION_APPWIDGET_THEME_CHANGED:
        case Constants.ACTION_APPWIDGET_SETTINGS_SHOW_CONTROLS:
            refreshWidgetValues(context);
            break;
        case Constants.ACTION_APPWIDGET_UPDATE_PERIOD_CHANGED:
            onEnabled(context);
            break;
        case Constants.ACTION_APPWIDGET_CHANGE_SETTINGS:
            onUpdate(context, widgetManager, new int[]{ widgetId});
            break;
    }

    if (intent.getAction().startsWith(Constants.ACTION_APPWIDGET_SETTINGS_OPENED)) {
        String[] params = intent.getAction().split("__");
        String widgetIdTxt = params[1];
        widgetId = Integer.parseInt(widgetIdTxt);
        openWidgetSettings(context, widgetId, params[2]);
    } else if (intent.getAction().startsWith(Constants.ACTION_APPWIDGET_START_ACTIVITY)) {
        AppPreference.setCurrentLocationId(context, currentLocation);
        Long widgetActionId = intent.getLongExtra("widgetAction", 1);
        Class activityClass = WidgetActions.getById(widgetActionId, "action_current_weather_icon").getActivityClass();
        Intent activityIntent = new Intent(context, activityClass);
        activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(activityIntent);
    } else if (intent.getAction().startsWith(Constants.ACTION_APPWIDGET_CHANGE_LOCATION)) {
        changeLocation(widgetId, locationsDbHelper, widgetSettingsDbHelper);
        GraphUtils.invalidateGraph();
        onUpdate(context, widgetManager, new int[]{widgetId});
    } else if (intent.getAction().startsWith(Constants.ACTION_FORCED_APPWIDGET_UPDATE)) {
        if (!WidgetRefreshIconService.isRotationActive) {
            sendWeatherUpdate(context, widgetId);
        }
        onUpdate(context, widgetManager, new int[]{ widgetId});

    }
}