Android Open Source - android-NSUWeather Weather Widget Provider






From Project

Back to project page android-NSUWeather.

License

The source code is released under:

MIT License

If you think the Android project android-NSUWeather listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * The MIT License (MIT)/* w w  w.j av a 2s .co m*/
 *
 * Copyright (c) 2014 Maxim Belsky
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.mbelsky.nsuweather.widgetprovider;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.mbelsky.nsuweather.R;
import com.mbelsky.nsuweather.preferences.Storage;
import com.mbelsky.nsuweather.service.UpdateWeatherService;
import com.mbelsky.nsuweather.utils.AppWidgetHelper;
import com.mbelsky.nsuweather.utils.Formatter;
import com.mbelsky.nsuweather.view.LastUpdateTimeView;
import com.mbelsky.nsuweather.view.NoConnectionView;
import com.mbelsky.nsuweather.view.TemperatureView;

import java.util.Date;

/**
 * User: mbelsky
 * Date: 23.08.13
 * Time: 2:07
 */
public class WeatherWidgetProvider extends AppWidgetProvider {

    public static final String WEATHER_UPDATED = "com.mbelsky.nsuweather.widgetprovider.WeatherDarkWidgetProvider.WEATHER_UPDATED";
    public static final String START_WEATHER_UPDATED = "com.mbelsky.nsuweather.widgetprovider.WeatherDarkWidgetProvider.START_WEATHER_UPDATED";

    @Override
    public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
        loadWeather(context);
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final String action = intent.getAction();
        if ( WEATHER_UPDATED.equals(action) ) {
            saveWeather(context, intent);
            updateWidgetView(context, false);
        } else if ( START_WEATHER_UPDATED.equals(action) ) {
            loadWeather(context);
        } else if ( ConnectivityManager.CONNECTIVITY_ACTION.equals(action) ) {
            onConnectivityAction(context);
        } else {
            super.onReceive(context, intent);
        }
    }

    /**
     * Start weather update if internet is available and data is old.
     */
    private void onConnectivityAction(final Context context) {
        ConnectivityManager connectivityManager =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        boolean internetIsAvailable = null != networkInfo && networkInfo.isConnected();
        if ( internetIsAvailable && Storage.getInstance(context).canBeUpdated() ) {
            loadWeather(context);
        }
    }

    /**
     * Update widget view and
     * start {@link com.mbelsky.nsuweather.service.UpdateWeatherService} for loading weather.
     */
    private void loadWeather(final Context context) {
        updateWidgetView(context, true);

        final Intent updateWeatherIntent = new Intent(context, UpdateWeatherService.class);
        context.startService(updateWeatherIntent);
    }

    private void saveWeather(final Context context, final Intent intent) {
        final boolean isSuccess =
                intent.getBooleanExtra(UpdateWeatherService.WEATHER_REQUEST_IS_SUCCESS_EXTRA_KEY,
                                       false);
        if ( !isSuccess ) {
            return;
        }
        final Storage storage = Storage.getInstance(context);
        final String temperature = intent
                .getStringExtra(UpdateWeatherService.WEATHER_TEMPERATURE_EXTRA_KEY);
        storage.setLastUpdateTime(new Date());
        storage.setLastTemperature(temperature);
        storage.save();
    }

    private void updateWidgetView(final Context context, final boolean isUpdating) {
        final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        final int[] appWidgetIds = AppWidgetHelper
                .getAppWidgetIds(context, appWidgetManager, WeatherWidgetProvider.class);

        if ( null != appWidgetIds && 0 != appWidgetIds.length ) {
            //widget has added at screen
            updateWidgetView(context, appWidgetManager, appWidgetIds, isUpdating);
        }
    }

    private void updateWidgetView(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds, final boolean isUpdating) {
        final RemoteViews remoteViews =
                new RemoteViews(context.getPackageName(), R.layout.widget_layout);

        final Storage storage = Storage.getInstance(context);
        final String date = Formatter.getLastUpdateTime(context, storage);
        final String lastTemperature = Formatter.getLastTemperature(storage);

        updateViewsVisibility(remoteViews, isUpdating);

        remoteViews.setOnClickPendingIntent(R.id.big_widget_container,
                                            getWeatherUpdateIntent(context));

        if ( isUpdating ) {
            appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
            return;
        }

        final Bitmap temperatureBitmap;
        if ( date.contains(Storage.DEFAULT_VALUE) ) {
            //Weather wasn't updated.
            temperatureBitmap = getNoConnectionBitmap(context);
        } else {
            temperatureBitmap = getTemperatureBitmap(context, lastTemperature);
        }
        remoteViews.setImageViewBitmap(R.id.big_widget_temperature, temperatureBitmap);
        remoteViews.setImageViewBitmap(R.id.big_widget_last_update_time,
                                       getLastUpdateBitmap(context, date));

        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

    /**
     * Update widget views visibility state.
     */
    private void updateViewsVisibility(final RemoteViews remoteViews, final boolean isUpdating) {
        final int progressBarVisibility;
        final int btnVisibility;
        final int lastUpdateLblVisibility;
        if ( isUpdating ) {
            progressBarVisibility = View.VISIBLE;
            btnVisibility = View.GONE;
            lastUpdateLblVisibility = View.GONE;
        } else {
            progressBarVisibility = View.GONE;
            btnVisibility = View.VISIBLE;
            lastUpdateLblVisibility = View.VISIBLE;
        }
        remoteViews.setViewVisibility(R.id.big_widget_refresh_weather_btn, btnVisibility);
        remoteViews.setViewVisibility(R.id.big_widget_refresh_weather_progress, progressBarVisibility);
        remoteViews.setViewVisibility(R.id.big_widget_last_update_time, lastUpdateLblVisibility);
    }

    private PendingIntent getWeatherUpdateIntent(final Context context) {
        final Intent intent = new Intent(START_WEATHER_UPDATED);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    }

    //Work with bitmaps bellow

    private Bitmap getTemperatureBitmap(final Context context, final String lastTemperature) {
        final TextView temperatureView = new TemperatureView(context);
        temperatureView.setText(Html.fromHtml(lastTemperature));

        assignSizeAndPosition(temperatureView);

        temperatureView.buildDrawingCache();
        return temperatureView.getDrawingCache();
    }

    private Bitmap getNoConnectionBitmap(final Context context) {
        final TextView noConnectionView = new NoConnectionView(context);

        assignSizeAndPosition(noConnectionView);

        noConnectionView.buildDrawingCache();
        return noConnectionView.getDrawingCache();
    }

    private Bitmap getLastUpdateBitmap(final Context context, final CharSequence lastUpdateTime) {
        final TextView lastUpdateTimeView = new LastUpdateTimeView(context);
        lastUpdateTimeView.setText(lastUpdateTime);

        assignSizeAndPosition(lastUpdateTimeView);

        lastUpdateTimeView.buildDrawingCache();
        return lastUpdateTimeView.getDrawingCache();
    }

    private void assignSizeAndPosition(final View view) {
        final int MODE;
        if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 ) {
            MODE = View.MeasureSpec.EXACTLY;
        } else {
            MODE = View.MeasureSpec.AT_MOST;
        }
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        view.measure(View.MeasureSpec.makeMeasureSpec(lp.width, MODE),
                     View.MeasureSpec.makeMeasureSpec(lp.height, MODE));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

    }
}




Java Source Code List

com.mbelsky.nsuweather.activity.SettingsActivity.java
com.mbelsky.nsuweather.http.NetworkConstants.java
com.mbelsky.nsuweather.http.parser.WeatherResponseParser.java
com.mbelsky.nsuweather.http.request.WeatherRequest.java
com.mbelsky.nsuweather.model.Weather.java
com.mbelsky.nsuweather.preferences.Storage.java
com.mbelsky.nsuweather.service.UpdateWeatherService.java
com.mbelsky.nsuweather.utils.AppWidgetHelper.java
com.mbelsky.nsuweather.utils.Formatter.java
com.mbelsky.nsuweather.utils.ViewHelper.java
com.mbelsky.nsuweather.view.LastUpdateTimeView.java
com.mbelsky.nsuweather.view.NoConnectionView.java
com.mbelsky.nsuweather.view.TemperatureView.java
com.mbelsky.nsuweather.widgetprovider.WeatherWidgetProvider.java