From: Gustavo Martin Morcuende Date: Sun, 16 Nov 2014 15:14:40 +0000 (+0100) Subject: WeatherInformation: updating class names X-Git-Tag: weatherinformation-1.0~61 X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=2b9c3fda30862b0d216de979732fc6ec6afa5948;p=AndroidWeatherInformation WeatherInformation: updating class names --- diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index fc89b93..ad09a72 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -59,7 +59,7 @@ android:supportsRtl="false" android:theme="@style/AppTheme" > @@ -70,8 +70,8 @@ + android:name=".activity.PreferencesActivity" + android:parentActivityName=".activity.MainTabsActivity" > @@ -85,7 +85,7 @@ + android:parentActivityName=".activity.MainTabsActivity" > @@ -95,7 +95,7 @@ + android:parentActivityName=".activity.MainTabsActivity" > @@ -113,7 +113,7 @@ + android:parentActivityName=".activity.MainTabsActivity" > @@ -131,7 +131,7 @@ @@ -155,7 +155,7 @@ diff --git a/app/src/main/java/name/gumartinm/weather/information/activity/MainTabsActivity.java b/app/src/main/java/name/gumartinm/weather/information/activity/MainTabsActivity.java new file mode 100644 index 0000000..11a3c5f --- /dev/null +++ b/app/src/main/java/name/gumartinm/weather/information/activity/MainTabsActivity.java @@ -0,0 +1,209 @@ +/** + * Copyright 2014 Gustavo Martin Morcuende + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package name.gumartinm.weather.information.activity; + +import android.app.ActionBar; +import android.app.ActionBar.Tab; +import android.app.FragmentTransaction; +import android.content.ComponentName; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentActivity; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentPagerAdapter; +import android.support.v4.view.ViewPager; +import android.view.Menu; +import android.view.MenuItem; + +import name.gumartinm.weather.information.R; +import name.gumartinm.weather.information.fragment.current.CurrentFragment; +import name.gumartinm.weather.information.fragment.overview.OverviewFragment; +import name.gumartinm.weather.information.model.DatabaseQueries; +import name.gumartinm.weather.information.model.WeatherLocation; + +import java.text.MessageFormat; +import java.util.Locale; + + +public class MainTabsActivity extends FragmentActivity { + private static final int NUM_ITEMS = 2; + private ViewPager mPager; + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.setContentView(R.layout.fragment_pager); + + this.mPager = (ViewPager)this.findViewById(R.id.pager); + this.mPager.setAdapter(new TabsAdapter(this.getSupportFragmentManager())); + + + this.mPager.setOnPageChangeListener( + new ViewPager.SimpleOnPageChangeListener() { + @Override + public void onPageSelected(final int position) { + MainTabsActivity.this.getActionBar().setSelectedNavigationItem(position); + } + }); + + + final ActionBar actionBar = this.getActionBar(); + + PreferenceManager.setDefaultValues(this, R.xml.weather_preferences, false); + + // Specify that tabs should be displayed in the action bar. + actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); + actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE); + actionBar.setDisplayHomeAsUpEnabled(true); + + // Create a tab listener that is called when the user changes tabs. + final ActionBar.TabListener tabListener = new ActionBar.TabListener() { + + @Override + public void onTabSelected(final Tab tab, final FragmentTransaction ft) { + MainTabsActivity.this.mPager.setCurrentItem(tab.getPosition()); + + } + + @Override + public void onTabUnselected(final Tab tab, final FragmentTransaction ft) { + + } + + @Override + public void onTabReselected(final Tab tab, final FragmentTransaction ft) { + + } + + }; + + actionBar.addTab(actionBar.newTab().setText("CURRENTLY").setTabListener(tabListener)); + actionBar.addTab(actionBar.newTab().setText("FORECAST").setTabListener(tabListener)); + } + + @Override + public boolean onCreateOptionsMenu(final Menu menu) { + + this.getMenuInflater().inflate(R.menu.weather_main_menu, menu); + + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(final MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + super.onOptionsItemSelected(item); + + Intent intent; + final int itemId = item.getItemId(); + if (itemId == R.id.weather_menu_settings) { + intent = new Intent("name.gumartinm.weather.information.WEATHERINFO") + .setComponent(new ComponentName("name.gumartinm.weather.information", + "name.gumartinm.weather.information.activity.WeatherInformationPreferencesActivity")); + this.startActivity(intent); + return true; + } else if (itemId == R.id.weather_menu_map) { + intent = new Intent("name.gumartinm.weather.information.WEATHERINFO"). + setComponent(new ComponentName("name.gumartinm.weather.information", + "name.gumartinm.weather.information.activity.MapActivity")); + this.startActivity(intent); + return true; + } else if (itemId == R.id.weather_menu_about) { + intent = new Intent("name.gumartinm.weather.information.WEATHERINFO"). + setComponent(new ComponentName("name.gumartinm.weather.information", + "name.gumartinm.weather.information.activity.AboutActivity")); + this.startActivity(intent); + return true; + } else { + } + + // TODO: calling again super method? + return super.onOptionsItemSelected(item); + } + + @Override + protected void onRestoreInstanceState(final Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + } + + + @Override + public void onResume() { + super.onResume(); + + final ActionBar actionBar = this.getActionBar(); + + // 1. Update title. + final DatabaseQueries query = new DatabaseQueries(this.getApplicationContext()); + final WeatherLocation weatherLocation = query.queryDataBase(); + if (weatherLocation != null) { + final String[] array = new String[2]; + array[0] = weatherLocation.getCity(); + array[1] = weatherLocation.getCountry(); + final MessageFormat message = new MessageFormat("{0},{1}", Locale.US); + final String cityCountry = message.format(array); + actionBar.setTitle(cityCountry); + } else { + actionBar.setTitle(this.getString(R.string.text_field_no_chosen_location)); + } + + // 2. Update forecast tab text. + final SharedPreferences sharedPreferences = PreferenceManager + .getDefaultSharedPreferences(this); + final String keyPreference = this.getString(R.string.weather_preferences_day_forecast_key); + final String value = sharedPreferences.getString(keyPreference, ""); + String humanValue = ""; + if (value.equals("5")) { + humanValue = "5 DAY FORECAST"; + } else if (value.equals("10")) { + humanValue = "10 DAY FORECAST"; + } else if (value.equals("14")) { + humanValue = "14 DAY FORECAST"; + } + actionBar.getTabAt(1).setText(humanValue); + } + + @Override + public void onSaveInstanceState(final Bundle savedInstanceState) { + super.onSaveInstanceState(savedInstanceState); + } + + private class TabsAdapter extends FragmentPagerAdapter { + public TabsAdapter(final FragmentManager fm) { + super(fm); + } + + @Override + public int getCount() { + return NUM_ITEMS; + } + + @Override + public Fragment getItem(final int position) { + if (position == 0) { + return new CurrentFragment(); + } else { + return new OverviewFragment(); + } + + } + } +} diff --git a/app/src/main/java/name/gumartinm/weather/information/activity/PreferencesActivity.java b/app/src/main/java/name/gumartinm/weather/information/activity/PreferencesActivity.java new file mode 100644 index 0000000..84d1e8f --- /dev/null +++ b/app/src/main/java/name/gumartinm/weather/information/activity/PreferencesActivity.java @@ -0,0 +1,44 @@ +/** + * Copyright 2014 Gustavo Martin Morcuende + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package name.gumartinm.weather.information.activity; + +import android.app.ActionBar; +import android.app.Activity; +import android.os.Bundle; + +import name.gumartinm.weather.information.R; +import name.gumartinm.weather.information.fragment.preferences.PreferencesFragment; + +public class PreferencesActivity extends Activity { + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + this.getFragmentManager() + .beginTransaction() + .replace(android.R.id.content, + new PreferencesFragment()).commit(); + } + + @Override + public void onResume() { + super.onResume(); + + final ActionBar actionBar = this.getActionBar(); + actionBar.setTitle(this.getString(R.string.weather_preferences_action_settings)); + } +} diff --git a/app/src/main/java/name/gumartinm/weather/information/activity/WeatherInformationPreferencesActivity.java b/app/src/main/java/name/gumartinm/weather/information/activity/WeatherInformationPreferencesActivity.java deleted file mode 100644 index 621ab25..0000000 --- a/app/src/main/java/name/gumartinm/weather/information/activity/WeatherInformationPreferencesActivity.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright 2014 Gustavo Martin Morcuende - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package name.gumartinm.weather.information.activity; - -import android.app.ActionBar; -import android.app.Activity; -import android.os.Bundle; - -import name.gumartinm.weather.information.R; -import name.gumartinm.weather.information.fragment.preferences.WeatherInformationPreferencesFragment; - -public class WeatherInformationPreferencesActivity extends Activity { - - @Override - protected void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - this.getFragmentManager() - .beginTransaction() - .replace(android.R.id.content, - new WeatherInformationPreferencesFragment()).commit(); - } - - @Override - public void onResume() { - super.onResume(); - - final ActionBar actionBar = this.getActionBar(); - actionBar.setTitle(this.getString(R.string.weather_preferences_action_settings)); - } -} diff --git a/app/src/main/java/name/gumartinm/weather/information/activity/WeatherTabsActivity.java b/app/src/main/java/name/gumartinm/weather/information/activity/WeatherTabsActivity.java deleted file mode 100644 index e5c5947..0000000 --- a/app/src/main/java/name/gumartinm/weather/information/activity/WeatherTabsActivity.java +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Copyright 2014 Gustavo Martin Morcuende - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package name.gumartinm.weather.information.activity; - -import android.app.ActionBar; -import android.app.ActionBar.Tab; -import android.app.FragmentTransaction; -import android.content.ComponentName; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentActivity; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentPagerAdapter; -import android.support.v4.view.ViewPager; -import android.view.Menu; -import android.view.MenuItem; - -import name.gumartinm.weather.information.R; -import name.gumartinm.weather.information.fragment.current.CurrentFragment; -import name.gumartinm.weather.information.fragment.overview.OverviewFragment; -import name.gumartinm.weather.information.model.DatabaseQueries; -import name.gumartinm.weather.information.model.WeatherLocation; - -import java.text.MessageFormat; -import java.util.Locale; - - -public class WeatherTabsActivity extends FragmentActivity { - private static final int NUM_ITEMS = 2; - private ViewPager mPager; - - @Override - protected void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - this.setContentView(R.layout.fragment_pager); - - this.mPager = (ViewPager)this.findViewById(R.id.pager); - this.mPager.setAdapter(new TabsAdapter(this.getSupportFragmentManager())); - - - this.mPager.setOnPageChangeListener( - new ViewPager.SimpleOnPageChangeListener() { - @Override - public void onPageSelected(final int position) { - WeatherTabsActivity.this.getActionBar().setSelectedNavigationItem(position); - } - }); - - - final ActionBar actionBar = this.getActionBar(); - - PreferenceManager.setDefaultValues(this, R.xml.weather_preferences, false); - - // Specify that tabs should be displayed in the action bar. - actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); - actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE); - actionBar.setDisplayHomeAsUpEnabled(true); - - // Create a tab listener that is called when the user changes tabs. - final ActionBar.TabListener tabListener = new ActionBar.TabListener() { - - @Override - public void onTabSelected(final Tab tab, final FragmentTransaction ft) { - WeatherTabsActivity.this.mPager.setCurrentItem(tab.getPosition()); - - } - - @Override - public void onTabUnselected(final Tab tab, final FragmentTransaction ft) { - - } - - @Override - public void onTabReselected(final Tab tab, final FragmentTransaction ft) { - - } - - }; - - actionBar.addTab(actionBar.newTab().setText("CURRENTLY").setTabListener(tabListener)); - actionBar.addTab(actionBar.newTab().setText("FORECAST").setTabListener(tabListener)); - } - - @Override - public boolean onCreateOptionsMenu(final Menu menu) { - - this.getMenuInflater().inflate(R.menu.weather_main_menu, menu); - - return super.onCreateOptionsMenu(menu); - } - - @Override - public boolean onOptionsItemSelected(final MenuItem item) { - // Handle action bar item clicks here. The action bar will - // automatically handle clicks on the Home/Up button, so long - // as you specify a parent activity in AndroidManifest.xml. - super.onOptionsItemSelected(item); - - Intent intent; - final int itemId = item.getItemId(); - if (itemId == R.id.weather_menu_settings) { - intent = new Intent("name.gumartinm.weather.information.WEATHERINFO") - .setComponent(new ComponentName("name.gumartinm.weather.information", - "name.gumartinm.weather.information.activity.WeatherInformationPreferencesActivity")); - this.startActivity(intent); - return true; - } else if (itemId == R.id.weather_menu_map) { - intent = new Intent("name.gumartinm.weather.information.WEATHERINFO"). - setComponent(new ComponentName("name.gumartinm.weather.information", - "name.gumartinm.weather.information.activity.MapActivity")); - this.startActivity(intent); - return true; - } else if (itemId == R.id.weather_menu_about) { - intent = new Intent("name.gumartinm.weather.information.WEATHERINFO"). - setComponent(new ComponentName("name.gumartinm.weather.information", - "name.gumartinm.weather.information.activity.AboutActivity")); - this.startActivity(intent); - return true; - } else { - } - - // TODO: calling again super method? - return super.onOptionsItemSelected(item); - } - - @Override - protected void onRestoreInstanceState(final Bundle savedInstanceState) { - super.onRestoreInstanceState(savedInstanceState); - } - - - @Override - public void onResume() { - super.onResume(); - - final ActionBar actionBar = this.getActionBar(); - - // 1. Update title. - final DatabaseQueries query = new DatabaseQueries(this.getApplicationContext()); - final WeatherLocation weatherLocation = query.queryDataBase(); - if (weatherLocation != null) { - final String[] array = new String[2]; - array[0] = weatherLocation.getCity(); - array[1] = weatherLocation.getCountry(); - final MessageFormat message = new MessageFormat("{0},{1}", Locale.US); - final String cityCountry = message.format(array); - actionBar.setTitle(cityCountry); - } else { - actionBar.setTitle(this.getString(R.string.text_field_no_chosen_location)); - } - - // 2. Update forecast tab text. - final SharedPreferences sharedPreferences = PreferenceManager - .getDefaultSharedPreferences(this); - final String keyPreference = this.getString(R.string.weather_preferences_day_forecast_key); - final String value = sharedPreferences.getString(keyPreference, ""); - String humanValue = ""; - if (value.equals("5")) { - humanValue = "5 DAY FORECAST"; - } else if (value.equals("10")) { - humanValue = "10 DAY FORECAST"; - } else if (value.equals("14")) { - humanValue = "14 DAY FORECAST"; - } - actionBar.getTabAt(1).setText(humanValue); - } - - @Override - public void onSaveInstanceState(final Bundle savedInstanceState) { - super.onSaveInstanceState(savedInstanceState); - } - - private class TabsAdapter extends FragmentPagerAdapter { - public TabsAdapter(final FragmentManager fm) { - super(fm); - } - - @Override - public int getCount() { - return NUM_ITEMS; - } - - @Override - public Fragment getItem(final int position) { - if (position == 0) { - return new CurrentFragment(); - } else { - return new OverviewFragment(); - } - - } - } -} diff --git a/app/src/main/java/name/gumartinm/weather/information/boot/BootReceiver.java b/app/src/main/java/name/gumartinm/weather/information/boot/BootReceiver.java new file mode 100644 index 0000000..462491f --- /dev/null +++ b/app/src/main/java/name/gumartinm/weather/information/boot/BootReceiver.java @@ -0,0 +1,75 @@ +/** + * Copyright 2014 Gustavo Martin Morcuende + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package name.gumartinm.weather.information.boot; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.SystemClock; +import android.preference.PreferenceManager; + +import name.gumartinm.weather.information.R; +import name.gumartinm.weather.information.notification.NotificationIntentService; + +public class BootReceiver extends BroadcastReceiver { + + @Override + public void onReceive(final Context context, final Intent intent) { + + if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { + + // Update Time Rate + final SharedPreferences sharedPreferences = PreferenceManager + .getDefaultSharedPreferences(context); + final String keyPreference = context + .getString(R.string.weather_preferences_update_time_rate_key); + final String updateTimeRate = sharedPreferences.getString(keyPreference, ""); + long chosenInterval = 0; + if (updateTimeRate.equals("900")) { + chosenInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES; + } else if (updateTimeRate.equals("1800")) { + chosenInterval = AlarmManager.INTERVAL_HALF_HOUR; + } else if (updateTimeRate.equals("3600")) { + chosenInterval = AlarmManager.INTERVAL_HOUR; + } else if (updateTimeRate.equals("43200")) { + chosenInterval = AlarmManager.INTERVAL_HALF_DAY; + } else if (updateTimeRate.equals("86400")) { + chosenInterval = AlarmManager.INTERVAL_DAY; + } + + if (chosenInterval != 0) { + final AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + // TODO: better use some string instead of .class? In case I change the service class + // this could be a problem (I guess) + final Intent serviceIntent = new Intent(context, NotificationIntentService.class); + final PendingIntent alarmIntent = PendingIntent.getService( + context, + 0, + serviceIntent, + PendingIntent.FLAG_UPDATE_CURRENT); + alarmMgr.setInexactRepeating( + AlarmManager.ELAPSED_REALTIME, + SystemClock.elapsedRealtime() + chosenInterval, + chosenInterval, + alarmIntent); + } + } + } + +} diff --git a/app/src/main/java/name/gumartinm/weather/information/boot/WeatherInformationBootReceiver.java b/app/src/main/java/name/gumartinm/weather/information/boot/WeatherInformationBootReceiver.java deleted file mode 100644 index 7ff2fb0..0000000 --- a/app/src/main/java/name/gumartinm/weather/information/boot/WeatherInformationBootReceiver.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright 2014 Gustavo Martin Morcuende - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package name.gumartinm.weather.information.boot; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.SystemClock; -import android.preference.PreferenceManager; - -import name.gumartinm.weather.information.R; -import name.gumartinm.weather.information.notification.NotificationIntentService; - -public class WeatherInformationBootReceiver extends BroadcastReceiver { - - @Override - public void onReceive(final Context context, final Intent intent) { - - if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { - - // Update Time Rate - final SharedPreferences sharedPreferences = PreferenceManager - .getDefaultSharedPreferences(context); - final String keyPreference = context - .getString(R.string.weather_preferences_update_time_rate_key); - final String updateTimeRate = sharedPreferences.getString(keyPreference, ""); - long chosenInterval = 0; - if (updateTimeRate.equals("900")) { - chosenInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES; - } else if (updateTimeRate.equals("1800")) { - chosenInterval = AlarmManager.INTERVAL_HALF_HOUR; - } else if (updateTimeRate.equals("3600")) { - chosenInterval = AlarmManager.INTERVAL_HOUR; - } else if (updateTimeRate.equals("43200")) { - chosenInterval = AlarmManager.INTERVAL_HALF_DAY; - } else if (updateTimeRate.equals("86400")) { - chosenInterval = AlarmManager.INTERVAL_DAY; - } - - if (chosenInterval != 0) { - final AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - // TODO: better use some string instead of .class? In case I change the service class - // this could be a problem (I guess) - final Intent serviceIntent = new Intent(context, NotificationIntentService.class); - final PendingIntent alarmIntent = PendingIntent.getService( - context, - 0, - serviceIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - alarmMgr.setInexactRepeating( - AlarmManager.ELAPSED_REALTIME, - SystemClock.elapsedRealtime() + chosenInterval, - chosenInterval, - alarmIntent); - } - } - } - -} diff --git a/app/src/main/java/name/gumartinm/weather/information/fragment/preferences/PreferencesFragment.java b/app/src/main/java/name/gumartinm/weather/information/fragment/preferences/PreferencesFragment.java new file mode 100644 index 0000000..3acd7f3 --- /dev/null +++ b/app/src/main/java/name/gumartinm/weather/information/fragment/preferences/PreferencesFragment.java @@ -0,0 +1,411 @@ +/** + * Copyright 2014 Gustavo Martin Morcuende + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package name.gumartinm.weather.information.fragment.preferences; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.OnSharedPreferenceChangeListener; +import android.os.Bundle; +import android.os.SystemClock; +import android.preference.Preference; +import android.preference.PreferenceFragment; +import android.preference.SwitchPreference; + +import name.gumartinm.weather.information.R; +import name.gumartinm.weather.information.notification.NotificationIntentService; + +public class PreferencesFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { + + @Override + public void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // Load the preferences from an XML resource + this.addPreferencesFromResource(R.xml.weather_preferences); + + + // Temperature units + String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature); + String[] humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); + String keyPreference = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_temperature_key); + Preference connectionPref = this.findPreference(keyPreference); + String value = this.getPreferenceManager().getSharedPreferences() + .getString(keyPreference, this.getString(R.string.weather_preferences_temperature_celsius)); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } + connectionPref.setSummary(humanValue); + + // Wind + values = this.getResources().getStringArray(R.array.weather_preferences_wind); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_wind_human_value); + keyPreference = this.getString(R.string.weather_preferences_wind_key); + connectionPref = this.findPreference(keyPreference); + value = this.getPreferenceManager().getSharedPreferences() + .getString(keyPreference, this.getString(R.string.weather_preferences_wind_meters)); + humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } + connectionPref.setSummary(humanValue); + + // Pressure + values = this.getResources().getStringArray(R.array.weather_preferences_pressure); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_pressure_human_value); + keyPreference = this.getString(R.string.weather_preferences_pressure_key); + connectionPref = this.findPreference(keyPreference); + value = this.getPreferenceManager().getSharedPreferences() + .getString(keyPreference, this.getString(R.string.weather_preferences_pressure_pascal)); + humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } + connectionPref.setSummary(humanValue); + + // Forecast days number + values = this.getResources().getStringArray(R.array.weather_preferences_day_forecast); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_day_forecast_human_value); + keyPreference = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_day_forecast_key); + connectionPref = this.findPreference(keyPreference); + value = this.getPreferenceManager().getSharedPreferences().getString(keyPreference, values[0]); + humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } + connectionPref.setSummary(humanValue); + + // Refresh interval + values = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval_human_value); + keyPreference = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_refresh_interval_key); + connectionPref = this.findPreference(keyPreference); + value = this.getPreferenceManager().getSharedPreferences().getString(keyPreference, values[0]); + humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } else if (value.equals(values[3])) { + humanValue = humanValues[3]; + } else if (value.equals(values[4])) { + humanValue = humanValues[4]; + } else if (value.equals(values[5])) { + humanValue = humanValues[5]; + } else if (value.equals(values[6])) { + humanValue = humanValues[6]; + } + connectionPref.setSummary(humanValue); + + // Update Time Rate + values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate_human_value); + keyPreference = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_update_time_rate_key); + connectionPref = this.findPreference(keyPreference); + value = this.getPreferenceManager().getSharedPreferences() + .getString(keyPreference, values[0]); + humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } else if (value.equals(values[3])) { + humanValue = humanValues[3]; + } else if (value.equals(values[4])) { + humanValue = humanValues[4]; + } + connectionPref.setSummary(humanValue); + + // Notifications temperature units + values = this.getResources().getStringArray(R.array.weather_preferences_temperature); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); + keyPreference = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_notifications_temperature_key); + connectionPref = this.findPreference(keyPreference); + value = this.getPreferenceManager().getSharedPreferences() + .getString(keyPreference, this.getString(R.string.weather_preferences_temperature_celsius)); + humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } + connectionPref.setSummary(humanValue); + } + + @Override + public void onResume() { + super.onResume(); + this.getPreferenceManager().getSharedPreferences() + .registerOnSharedPreferenceChangeListener(this); + + } + + @Override + public void onPause() { + super.onPause(); + this.getPreferenceManager().getSharedPreferences() + .unregisterOnSharedPreferenceChangeListener(this); + } + + @Override + public void onSharedPreferenceChanged( + final SharedPreferences sharedPreferences, final String key) { + + // Temperature units + String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature); + String[] humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); + String keyValue = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_temperature_key); + if (key.equals(keyValue)) { + final Preference connectionPref = this.findPreference(key); + final String value = sharedPreferences.getString(key, values[0]); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } + + connectionPref.setSummary(humanValue); + return; + } + + // Wind + values = this.getResources().getStringArray(R.array.weather_preferences_wind); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_wind_human_value); + keyValue = this.getString(R.string.weather_preferences_wind_key); + if (key.equals(keyValue)) { + final Preference connectionPref = this.findPreference(key); + final String value = sharedPreferences.getString(key, values[0]); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } + + connectionPref.setSummary(humanValue); + return; + } + + // Pressure + values = this.getResources().getStringArray(R.array.weather_preferences_pressure); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_pressure_human_value); + keyValue = this.getString(R.string.weather_preferences_pressure_key); + if (key.equals(keyValue)) { + final Preference connectionPref = this.findPreference(key); + final String value = sharedPreferences.getString(key, values[0]); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } + + connectionPref.setSummary(humanValue); + return; + } + + // Forecast days number + values = this.getResources().getStringArray(R.array.weather_preferences_day_forecast); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_day_forecast_human_value); + keyValue = this.getActivity().getString( + R.string.weather_preferences_day_forecast_key); + if (key.equals(keyValue)) { + final Preference connectionPref = this.findPreference(key); + final String value = sharedPreferences.getString(key, values[0]); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } + connectionPref.setSummary(humanValue); + return; + } + + // Refresh interval + values = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval_human_value); + keyValue = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_refresh_interval_key); + if (key.equals(keyValue)) { + final Preference connectionPref = this.findPreference(key); + final String value = sharedPreferences.getString(key, values[0]); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } else if (value.equals(values[3])) { + humanValue = humanValues[3]; + } else if (value.equals(values[4])) { + humanValue = humanValues[4]; + } else if (value.equals(values[5])) { + humanValue = humanValues[5]; + } else if (value.equals(values[6])) { + humanValue = humanValues[6]; + } + connectionPref.setSummary(humanValue); + return; + } + + // Notification switch + values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); + keyValue = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_notifications_switch_key); + if (key.equals(keyValue)) { + final SwitchPreference preference = (SwitchPreference)this.findPreference(key); + if (preference.isChecked()) + { + keyValue = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_update_time_rate_key); + final String value = sharedPreferences.getString(keyValue, values[0]); + this.updateNotification(value); + } else { + this.cancelNotification(); + } + } + // Update Time Rate + values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate_human_value); + keyValue = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_update_time_rate_key); + if (key.equals(keyValue)) { + final Preference connectionPref = this.findPreference(key); + final String value = sharedPreferences.getString(key, values[0]); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } else if (value.equals(values[3])) { + humanValue = humanValues[3]; + } else if (value.equals(values[4])) { + humanValue = humanValues[4]; + } + + this.updateNotification(value); + connectionPref.setSummary(humanValue); + return; + } + + // Temperature units + values = this.getResources().getStringArray(R.array.weather_preferences_temperature); + humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); + keyValue = this.getActivity().getApplicationContext().getString( + R.string.weather_preferences_notifications_temperature_key); + if (key.equals(keyValue)) { + final Preference connectionPref = this.findPreference(key); + final String value = sharedPreferences.getString(key, values[0]); + String humanValue = ""; + if (value.equals(values[0])) { + humanValue = humanValues[0]; + } else if (value.equals(values[1])) { + humanValue = humanValues[1]; + } else if (value.equals(values[2])) { + humanValue = humanValues[2]; + } + + connectionPref.setSummary(humanValue); + return; + } + } + + private void updateNotification(final String updateTimeRate) { + final String[] values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); + long chosenInterval = 0; + if (updateTimeRate.equals(values[0])) { + chosenInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES; + } else if (updateTimeRate.equals(values[1])) { + chosenInterval = AlarmManager.INTERVAL_HALF_HOUR; + } else if (updateTimeRate.equals(values[2])) { + chosenInterval = AlarmManager.INTERVAL_HOUR; + } else if (updateTimeRate.equals(values[3])) { + chosenInterval = AlarmManager.INTERVAL_HALF_DAY; + } else if (updateTimeRate.equals(values[4])) { + chosenInterval = AlarmManager.INTERVAL_DAY; + } + + final AlarmManager alarmMgr = + (AlarmManager) this.getActivity().getApplicationContext().getSystemService(Context.ALARM_SERVICE); + // TODO: better use some string instead of .class? In case I change the service class + // this could be a problem (I guess) + final Intent serviceIntent = + new Intent(this.getActivity().getApplicationContext(), NotificationIntentService.class); + final PendingIntent alarmIntent = + PendingIntent.getService( + this.getActivity().getApplicationContext(), + 0, + serviceIntent, + PendingIntent.FLAG_UPDATE_CURRENT); + if (chosenInterval != 0) { + alarmMgr.setInexactRepeating( + AlarmManager.ELAPSED_REALTIME, + SystemClock.elapsedRealtime(), + chosenInterval, + alarmIntent); + } + } + + private void cancelNotification() { + final AlarmManager alarmMgr = + (AlarmManager) this.getActivity().getApplicationContext().getSystemService(Context.ALARM_SERVICE); + final Intent serviceIntent = + new Intent(this.getActivity().getApplicationContext(), NotificationIntentService.class); + final PendingIntent alarmIntent = + PendingIntent.getService( + this.getActivity().getApplicationContext(), + 0, + serviceIntent, + PendingIntent.FLAG_UPDATE_CURRENT); + alarmMgr.cancel(alarmIntent); + } +} diff --git a/app/src/main/java/name/gumartinm/weather/information/fragment/preferences/WeatherInformationPreferencesFragment.java b/app/src/main/java/name/gumartinm/weather/information/fragment/preferences/WeatherInformationPreferencesFragment.java deleted file mode 100644 index 9fbd25a..0000000 --- a/app/src/main/java/name/gumartinm/weather/information/fragment/preferences/WeatherInformationPreferencesFragment.java +++ /dev/null @@ -1,412 +0,0 @@ -/** - * Copyright 2014 Gustavo Martin Morcuende - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package name.gumartinm.weather.information.fragment.preferences; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; -import android.os.Bundle; -import android.os.SystemClock; -import android.preference.Preference; -import android.preference.PreferenceFragment; -import android.preference.SwitchPreference; - -import name.gumartinm.weather.information.R; -import name.gumartinm.weather.information.notification.NotificationIntentService; - -public class WeatherInformationPreferencesFragment extends PreferenceFragment - implements OnSharedPreferenceChangeListener { - - @Override - public void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - // Load the preferences from an XML resource - this.addPreferencesFromResource(R.xml.weather_preferences); - - - // Temperature units - String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature); - String[] humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); - String keyPreference = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_temperature_key); - Preference connectionPref = this.findPreference(keyPreference); - String value = this.getPreferenceManager().getSharedPreferences() - .getString(keyPreference, this.getString(R.string.weather_preferences_temperature_celsius)); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } - connectionPref.setSummary(humanValue); - - // Wind - values = this.getResources().getStringArray(R.array.weather_preferences_wind); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_wind_human_value); - keyPreference = this.getString(R.string.weather_preferences_wind_key); - connectionPref = this.findPreference(keyPreference); - value = this.getPreferenceManager().getSharedPreferences() - .getString(keyPreference, this.getString(R.string.weather_preferences_wind_meters)); - humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } - connectionPref.setSummary(humanValue); - - // Pressure - values = this.getResources().getStringArray(R.array.weather_preferences_pressure); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_pressure_human_value); - keyPreference = this.getString(R.string.weather_preferences_pressure_key); - connectionPref = this.findPreference(keyPreference); - value = this.getPreferenceManager().getSharedPreferences() - .getString(keyPreference, this.getString(R.string.weather_preferences_pressure_pascal)); - humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } - connectionPref.setSummary(humanValue); - - // Forecast days number - values = this.getResources().getStringArray(R.array.weather_preferences_day_forecast); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_day_forecast_human_value); - keyPreference = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_day_forecast_key); - connectionPref = this.findPreference(keyPreference); - value = this.getPreferenceManager().getSharedPreferences().getString(keyPreference, values[0]); - humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } - connectionPref.setSummary(humanValue); - - // Refresh interval - values = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval_human_value); - keyPreference = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_refresh_interval_key); - connectionPref = this.findPreference(keyPreference); - value = this.getPreferenceManager().getSharedPreferences().getString(keyPreference, values[0]); - humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } else if (value.equals(values[3])) { - humanValue = humanValues[3]; - } else if (value.equals(values[4])) { - humanValue = humanValues[4]; - } else if (value.equals(values[5])) { - humanValue = humanValues[5]; - } else if (value.equals(values[6])) { - humanValue = humanValues[6]; - } - connectionPref.setSummary(humanValue); - - // Update Time Rate - values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate_human_value); - keyPreference = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_update_time_rate_key); - connectionPref = this.findPreference(keyPreference); - value = this.getPreferenceManager().getSharedPreferences() - .getString(keyPreference, values[0]); - humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } else if (value.equals(values[3])) { - humanValue = humanValues[3]; - } else if (value.equals(values[4])) { - humanValue = humanValues[4]; - } - connectionPref.setSummary(humanValue); - - // Notifications temperature units - values = this.getResources().getStringArray(R.array.weather_preferences_temperature); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); - keyPreference = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_notifications_temperature_key); - connectionPref = this.findPreference(keyPreference); - value = this.getPreferenceManager().getSharedPreferences() - .getString(keyPreference, this.getString(R.string.weather_preferences_temperature_celsius)); - humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } - connectionPref.setSummary(humanValue); - } - - @Override - public void onResume() { - super.onResume(); - this.getPreferenceManager().getSharedPreferences() - .registerOnSharedPreferenceChangeListener(this); - - } - - @Override - public void onPause() { - super.onPause(); - this.getPreferenceManager().getSharedPreferences() - .unregisterOnSharedPreferenceChangeListener(this); - } - - @Override - public void onSharedPreferenceChanged( - final SharedPreferences sharedPreferences, final String key) { - - // Temperature units - String[] values = this.getResources().getStringArray(R.array.weather_preferences_temperature); - String[] humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); - String keyValue = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_temperature_key); - if (key.equals(keyValue)) { - final Preference connectionPref = this.findPreference(key); - final String value = sharedPreferences.getString(key, values[0]); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } - - connectionPref.setSummary(humanValue); - return; - } - - // Wind - values = this.getResources().getStringArray(R.array.weather_preferences_wind); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_wind_human_value); - keyValue = this.getString(R.string.weather_preferences_wind_key); - if (key.equals(keyValue)) { - final Preference connectionPref = this.findPreference(key); - final String value = sharedPreferences.getString(key, values[0]); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } - - connectionPref.setSummary(humanValue); - return; - } - - // Pressure - values = this.getResources().getStringArray(R.array.weather_preferences_pressure); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_pressure_human_value); - keyValue = this.getString(R.string.weather_preferences_pressure_key); - if (key.equals(keyValue)) { - final Preference connectionPref = this.findPreference(key); - final String value = sharedPreferences.getString(key, values[0]); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } - - connectionPref.setSummary(humanValue); - return; - } - - // Forecast days number - values = this.getResources().getStringArray(R.array.weather_preferences_day_forecast); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_day_forecast_human_value); - keyValue = this.getActivity().getString( - R.string.weather_preferences_day_forecast_key); - if (key.equals(keyValue)) { - final Preference connectionPref = this.findPreference(key); - final String value = sharedPreferences.getString(key, values[0]); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } - connectionPref.setSummary(humanValue); - return; - } - - // Refresh interval - values = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_refresh_interval_human_value); - keyValue = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_refresh_interval_key); - if (key.equals(keyValue)) { - final Preference connectionPref = this.findPreference(key); - final String value = sharedPreferences.getString(key, values[0]); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } else if (value.equals(values[3])) { - humanValue = humanValues[3]; - } else if (value.equals(values[4])) { - humanValue = humanValues[4]; - } else if (value.equals(values[5])) { - humanValue = humanValues[5]; - } else if (value.equals(values[6])) { - humanValue = humanValues[6]; - } - connectionPref.setSummary(humanValue); - return; - } - - // Notification switch - values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); - keyValue = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_notifications_switch_key); - if (key.equals(keyValue)) { - final SwitchPreference preference = (SwitchPreference)this.findPreference(key); - if (preference.isChecked()) - { - keyValue = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_update_time_rate_key); - final String value = sharedPreferences.getString(keyValue, values[0]); - this.updateNotification(value); - } else { - this.cancelNotification(); - } - } - // Update Time Rate - values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate_human_value); - keyValue = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_update_time_rate_key); - if (key.equals(keyValue)) { - final Preference connectionPref = this.findPreference(key); - final String value = sharedPreferences.getString(key, values[0]); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } else if (value.equals(values[3])) { - humanValue = humanValues[3]; - } else if (value.equals(values[4])) { - humanValue = humanValues[4]; - } - - this.updateNotification(value); - connectionPref.setSummary(humanValue); - return; - } - - // Temperature units - values = this.getResources().getStringArray(R.array.weather_preferences_temperature); - humanValues = this.getResources().getStringArray(R.array.weather_preferences_temperature_human_value); - keyValue = this.getActivity().getApplicationContext().getString( - R.string.weather_preferences_notifications_temperature_key); - if (key.equals(keyValue)) { - final Preference connectionPref = this.findPreference(key); - final String value = sharedPreferences.getString(key, values[0]); - String humanValue = ""; - if (value.equals(values[0])) { - humanValue = humanValues[0]; - } else if (value.equals(values[1])) { - humanValue = humanValues[1]; - } else if (value.equals(values[2])) { - humanValue = humanValues[2]; - } - - connectionPref.setSummary(humanValue); - return; - } - } - - private void updateNotification(final String updateTimeRate) { - final String[] values = this.getResources().getStringArray(R.array.weather_preferences_update_time_rate); - long chosenInterval = 0; - if (updateTimeRate.equals(values[0])) { - chosenInterval = AlarmManager.INTERVAL_FIFTEEN_MINUTES; - } else if (updateTimeRate.equals(values[1])) { - chosenInterval = AlarmManager.INTERVAL_HALF_HOUR; - } else if (updateTimeRate.equals(values[2])) { - chosenInterval = AlarmManager.INTERVAL_HOUR; - } else if (updateTimeRate.equals(values[3])) { - chosenInterval = AlarmManager.INTERVAL_HALF_DAY; - } else if (updateTimeRate.equals(values[4])) { - chosenInterval = AlarmManager.INTERVAL_DAY; - } - - final AlarmManager alarmMgr = - (AlarmManager) this.getActivity().getApplicationContext().getSystemService(Context.ALARM_SERVICE); - // TODO: better use some string instead of .class? In case I change the service class - // this could be a problem (I guess) - final Intent serviceIntent = - new Intent(this.getActivity().getApplicationContext(), NotificationIntentService.class); - final PendingIntent alarmIntent = - PendingIntent.getService( - this.getActivity().getApplicationContext(), - 0, - serviceIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - if (chosenInterval != 0) { - alarmMgr.setInexactRepeating( - AlarmManager.ELAPSED_REALTIME, - SystemClock.elapsedRealtime(), - chosenInterval, - alarmIntent); - } - } - - private void cancelNotification() { - final AlarmManager alarmMgr = - (AlarmManager) this.getActivity().getApplicationContext().getSystemService(Context.ALARM_SERVICE); - final Intent serviceIntent = - new Intent(this.getActivity().getApplicationContext(), NotificationIntentService.class); - final PendingIntent alarmIntent = - PendingIntent.getService( - this.getActivity().getApplicationContext(), - 0, - serviceIntent, - PendingIntent.FLAG_UPDATE_CURRENT); - alarmMgr.cancel(alarmIntent); - } -} diff --git a/app/src/main/java/name/gumartinm/weather/information/notification/NotificationIntentService.java b/app/src/main/java/name/gumartinm/weather/information/notification/NotificationIntentService.java index bf7d7db..1ed1431 100644 --- a/app/src/main/java/name/gumartinm/weather/information/notification/NotificationIntentService.java +++ b/app/src/main/java/name/gumartinm/weather/information/notification/NotificationIntentService.java @@ -42,7 +42,7 @@ import android.widget.RemoteViews; import com.fasterxml.jackson.core.JsonParseException; import name.gumartinm.weather.information.R; -import name.gumartinm.weather.information.activity.WeatherTabsActivity; +import name.gumartinm.weather.information.activity.MainTabsActivity; import name.gumartinm.weather.information.httpclient.CustomHTTPClient; import name.gumartinm.weather.information.model.DatabaseQueries; import name.gumartinm.weather.information.model.WeatherLocation; @@ -203,7 +203,7 @@ public class NotificationIntentService extends IntentService { remoteView.setTextViewText(R.id.weather_notification_country, country); // 5. Activity launcher. - final Intent resultIntent = new Intent(this.getApplicationContext(), WeatherTabsActivity.class); + final Intent resultIntent = new Intent(this.getApplicationContext(), MainTabsActivity.class); // The PendingIntent to launch our activity if the user selects this notification // final PendingIntent contentIntent = PendingIntent.getActivity( // this.getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); @@ -212,7 +212,7 @@ public class NotificationIntentService extends IntentService { // your application to the Home screen. final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext()); // Adds the back stack for the Intent (but not the Intent itself) - stackBuilder.addParentStack(WeatherTabsActivity.class); + stackBuilder.addParentStack(MainTabsActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); final PendingIntent resultPendingIntent = diff --git a/app/src/main/java/name/gumartinm/weather/information/widget/WidgetIntentService.java b/app/src/main/java/name/gumartinm/weather/information/widget/WidgetIntentService.java new file mode 100644 index 0000000..c97740e --- /dev/null +++ b/app/src/main/java/name/gumartinm/weather/information/widget/WidgetIntentService.java @@ -0,0 +1,328 @@ +package name.gumartinm.weather.information.widget; + +import android.app.IntentService; +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.content.Context; +import android.content.Intent; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.net.Uri; +import android.net.http.AndroidHttpClient; +import android.support.v4.app.TaskStackBuilder; +import android.util.Log; +import android.view.View; +import android.widget.RemoteViews; + +import com.fasterxml.jackson.core.JsonParseException; +import name.gumartinm.weather.information.R; +import name.gumartinm.weather.information.httpclient.CustomHTTPClient; +import name.gumartinm.weather.information.model.DatabaseQueries; +import name.gumartinm.weather.information.model.WeatherLocation; +import name.gumartinm.weather.information.model.currentweather.Current; +import name.gumartinm.weather.information.parser.JPOSCurrentParser; +import name.gumartinm.weather.information.service.IconsList; +import name.gumartinm.weather.information.service.PermanentStorage; +import name.gumartinm.weather.information.service.ServiceCurrentParser; +import name.gumartinm.weather.information.widget.WidgetConfigure; + +import org.apache.http.client.ClientProtocolException; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.util.Date; +import java.util.Locale; + +public class WidgetIntentService extends IntentService { + private static final String TAG = "WidgetIntentService"; + private static final long UPDATE_TIME_RATE = 86400000L; + + public WidgetIntentService() { + super("WIS-Thread"); + } + + @Override + protected void onHandleIntent(final Intent intent) { + Log.i(TAG, "onHandleIntent"); + final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + final boolean isRefreshAppWidget = intent.getBooleanExtra("refreshAppWidget", false); + + if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { + // Nothing to do. Something went wrong. Show error. + return; + } + + + final DatabaseQueries query = new DatabaseQueries(this.getApplicationContext()); + final WeatherLocation weatherLocation = query.queryDataBase(); + + if (weatherLocation == null) { + // Nothing to do. Show error. + final RemoteViews view = this.makeErrorView(appWidgetId); + this.updateWidget(view, appWidgetId); + return; + } + + // TODO: improve this code. Too tired right now... + if (!isRefreshAppWidget) { + RemoteViews view; + + final PermanentStorage store = new PermanentStorage(this.getApplicationContext()); + final Current current = store.getWidgetCurrentData(appWidgetId); + if (current != null) { + // Update UI. + view = this.makeView(current, weatherLocation, appWidgetId); + } else { + // Show error. + view = this.makeErrorView(appWidgetId); + } + this.updateWidget(view, appWidgetId); + } else { + RemoteViews view; + + final Current current = this.getRemoteCurrent(weatherLocation); + if (current != null) { + // Update UI. + view = this.makeView(current, weatherLocation, appWidgetId); + + final PermanentStorage store = new PermanentStorage(this.getApplicationContext()); + store.saveWidgetCurrentData(current, appWidgetId); + } else { + // Show error. + view = this.makeErrorView(appWidgetId); + } + this.updateWidget(view, appWidgetId); + } + } + + public static void deleteWidgetCurrentData(final Context context, final int appWidgetId) { + final PermanentStorage store = new PermanentStorage(context.getApplicationContext()); + + store.removeWidgetCurrentData(appWidgetId); + } + + private Current getRemoteCurrent(final WeatherLocation weatherLocation) { + + final ServiceCurrentParser weatherService = new ServiceCurrentParser(new JPOSCurrentParser()); + final CustomHTTPClient HTTPClient = new CustomHTTPClient( + AndroidHttpClient.newInstance("Android 4.3 WeatherInformation Agent")); + + try { + return this.getRemoteCurrentThrowable(weatherLocation, HTTPClient, weatherService); + + } catch (final JsonParseException e) { + Log.e(TAG, "doInBackground exception: ", e); + } catch (final ClientProtocolException e) { + Log.e(TAG, "doInBackground exception: ", e); + } catch (final MalformedURLException e) { + Log.e(TAG, "doInBackground exception: ", e); + } catch (final URISyntaxException e) { + Log.e(TAG, "doInBackground exception: ", e); + } catch (final IOException e) { + // logger infrastructure swallows UnknownHostException :/ + Log.e(TAG, "doInBackground exception: " + e.getMessage(), e); + } finally { + HTTPClient.close(); + } + + return null; + } + + private Current getRemoteCurrentThrowable(final WeatherLocation weatherLocation, + final CustomHTTPClient HTTPClient, final ServiceCurrentParser weatherService) + throws ClientProtocolException, MalformedURLException, URISyntaxException, + JsonParseException, IOException { + + final String APIVersion = this.getResources().getString(R.string.api_version); + + final String urlAPI = this.getResources().getString(R.string.uri_api_weather_today); + final String url = weatherService.createURIAPICurrent(urlAPI, APIVersion, + weatherLocation.getLatitude(), weatherLocation.getLongitude()); + final String urlWithoutCache = url.concat("&time=" + System.currentTimeMillis()); + final String jsonData = HTTPClient.retrieveDataAsString(new URL(urlWithoutCache)); + + return weatherService.retrieveCurrentFromJPOS(jsonData); + } + + private interface UnitsConversor { + + public double doConversion(final double value); + } + + private RemoteViews makeView(final Current current, final WeatherLocation weatherLocation, final int appWidgetId) { + + // TODO: repeating the same code in Overview, Specific and Current!!! + // 1. Update units of measurement. + + UnitsConversor tempUnitsConversor; + String keyPreference = this.getApplicationContext().getString(R.string.widget_preferences_temperature_units_key); + String realKeyPreference = keyPreference + "_" + appWidgetId; + // What was saved to permanent storage (or default values if it is the first time) + final int tempValue = this.getSharedPreferences("WIDGET_PREFERENCES", Context.MODE_PRIVATE).getInt(realKeyPreference, 0); + final String tempSymbol = this.getResources().getStringArray(R.array.weather_preferences_temperature)[tempValue]; + if (tempValue == 0) { + tempUnitsConversor = new UnitsConversor(){ + + @Override + public double doConversion(final double value) { + return value - 273.15; + } + + }; + } else if (tempValue == 1) { + tempUnitsConversor = new UnitsConversor(){ + + @Override + public double doConversion(final double value) { + return (value * 1.8) - 459.67; + } + + }; + } else { + tempUnitsConversor = new UnitsConversor(){ + + @Override + public double doConversion(final double value) { + return value; + } + + }; + } + + + // 2. Update country. + keyPreference = this.getApplicationContext().getString(R.string.widget_preferences_country_switch_key); + realKeyPreference = keyPreference + "_" + appWidgetId; + // What was saved to permanent storage (or default values if it is the first time) + final boolean isCountry = this.getSharedPreferences("WIDGET_PREFERENCES", Context.MODE_PRIVATE) + .getBoolean(realKeyPreference, false); + + + // 3. Formatters + final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US); + tempFormatter.applyPattern("#####.#####"); + + + // 4. Prepare data for RemoteViews. + String tempMax = ""; + if (current.getMain().getTemp_max() != null) { + double conversion = (Double) current.getMain().getTemp_max(); + conversion = tempUnitsConversor.doConversion(conversion); + tempMax = tempFormatter.format(conversion) + tempSymbol; + } + String tempMin = ""; + if (current.getMain().getTemp_min() != null) { + double conversion = (Double) current.getMain().getTemp_min(); + conversion = tempUnitsConversor.doConversion(conversion); + tempMin = tempFormatter.format(conversion) + tempSymbol; + } + Bitmap picture; + if ((current.getWeather().size() > 0) + && (current.getWeather().get(0).getIcon() != null) + && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) { + final String icon = current.getWeather().get(0).getIcon(); + picture = BitmapFactory.decodeResource(this.getResources(), IconsList.getIcon(icon) + .getResourceDrawable()); + } else { + picture = BitmapFactory.decodeResource(this.getResources(), + R.drawable.weather_severe_alert); + } + final String city = weatherLocation.getCity(); + final String country = weatherLocation.getCountry(); + + // 5. Insert data in RemoteViews. + final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget); + remoteView.setImageViewBitmap(R.id.weather_appwidget_image, picture); + remoteView.setTextViewText(R.id.weather_appwidget_temperature_max, tempMax); + remoteView.setTextViewText(R.id.weather_appwidget_temperature_min, tempMin); + remoteView.setTextViewText(R.id.weather_appwidget_city, city); + if (!isCountry) { + remoteView.setViewVisibility(R.id.weather_appwidget_country, View.GONE); + } else { + // TODO: It is as if Android had a view cache. If I did not set VISIBLE value, + // the country field would be gone forever... :/ + remoteView.setViewVisibility(R.id.weather_appwidget_country, View.VISIBLE); + remoteView.setTextViewText(R.id.weather_appwidget_country, country); + } + + + // 6. Activity launcher. + final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class); + resultIntent.putExtra("actionFromUser", true); + resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); + // resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK ); + // From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget + final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId)); + resultIntent.setData(data); + + final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext()); + // Adds the back stack for the Intent (but not the Intent itself) + stackBuilder.addParentStack(WidgetConfigure.class); + // Adds the Intent that starts the Activity to the top of the stack + stackBuilder.addNextIntent(resultIntent); + final PendingIntent resultPendingIntent = + stackBuilder.getPendingIntent( + 0, + PendingIntent.FLAG_UPDATE_CURRENT + ); + remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent); +// final PendingIntent resultPendingIntent = PendingIntent.getActivity( +// this.getApplicationContext(), +// 0, +// resultIntent, +// PendingIntent.FLAG_UPDATE_CURRENT); +// remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent); + + return remoteView; + } + + private RemoteViews makeErrorView(final int appWidgetId) { + final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget_error); + + // 6. Activity launcher. + final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class); + resultIntent.putExtra("actionFromUser", true); + resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); +// resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK ); + // From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget + final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId)); + resultIntent.setData(data); + + final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext()); + // Adds the back stack for the Intent (but not the Intent itself) + stackBuilder.addParentStack(WidgetConfigure.class); + // Adds the Intent that starts the Activity to the top of the stack + stackBuilder.addNextIntent(resultIntent); + final PendingIntent resultPendingIntent = + stackBuilder.getPendingIntent( + 0, + PendingIntent.FLAG_UPDATE_CURRENT + ); + remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent); +// final PendingIntent resultPendingIntent = PendingIntent.getActivity( +// this.getApplicationContext(), +// 0, +// resultIntent, +// PendingIntent.FLAG_UPDATE_CURRENT); +// remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent); + + return remoteView; + } + + private void updateWidget(final RemoteViews remoteView, final int appWidgetId) { + + final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext()); + manager.updateAppWidget(appWidgetId, remoteView); + } + +// private void updateWidgets(final RemoteViews remoteView) { +// +// final ComponentName widgets = new ComponentName(this.getApplicationContext(), WidgetProvider.class); +// final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext()); +// manager.updateAppWidget(widgets, remoteView); +// } +} diff --git a/app/src/main/java/name/gumartinm/weather/information/widget/WidgetProvider.java b/app/src/main/java/name/gumartinm/weather/information/widget/WidgetProvider.java index 628dbcf..c22f01c 100644 --- a/app/src/main/java/name/gumartinm/weather/information/widget/WidgetProvider.java +++ b/app/src/main/java/name/gumartinm/weather/information/widget/WidgetProvider.java @@ -9,8 +9,6 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; -import name.gumartinm.weather.information.widget.service.WidgetIntentService; - public class WidgetProvider extends AppWidgetProvider { @Override diff --git a/app/src/main/java/name/gumartinm/weather/information/widget/service/WidgetIntentService.java b/app/src/main/java/name/gumartinm/weather/information/widget/service/WidgetIntentService.java deleted file mode 100644 index 7de46e0..0000000 --- a/app/src/main/java/name/gumartinm/weather/information/widget/service/WidgetIntentService.java +++ /dev/null @@ -1,328 +0,0 @@ -package name.gumartinm.weather.information.widget.service; - -import android.app.IntentService; -import android.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.content.Context; -import android.content.Intent; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.net.Uri; -import android.net.http.AndroidHttpClient; -import android.support.v4.app.TaskStackBuilder; -import android.util.Log; -import android.view.View; -import android.widget.RemoteViews; - -import com.fasterxml.jackson.core.JsonParseException; -import name.gumartinm.weather.information.R; -import name.gumartinm.weather.information.httpclient.CustomHTTPClient; -import name.gumartinm.weather.information.model.DatabaseQueries; -import name.gumartinm.weather.information.model.WeatherLocation; -import name.gumartinm.weather.information.model.currentweather.Current; -import name.gumartinm.weather.information.parser.JPOSCurrentParser; -import name.gumartinm.weather.information.service.IconsList; -import name.gumartinm.weather.information.service.PermanentStorage; -import name.gumartinm.weather.information.service.ServiceCurrentParser; -import name.gumartinm.weather.information.widget.WidgetConfigure; - -import org.apache.http.client.ClientProtocolException; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.Date; -import java.util.Locale; - -public class WidgetIntentService extends IntentService { - private static final String TAG = "WidgetIntentService"; - private static final long UPDATE_TIME_RATE = 86400000L; - - public WidgetIntentService() { - super("WIS-Thread"); - } - - @Override - protected void onHandleIntent(final Intent intent) { - Log.i(TAG, "onHandleIntent"); - final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); - final boolean isRefreshAppWidget = intent.getBooleanExtra("refreshAppWidget", false); - - if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) { - // Nothing to do. Something went wrong. Show error. - return; - } - - - final DatabaseQueries query = new DatabaseQueries(this.getApplicationContext()); - final WeatherLocation weatherLocation = query.queryDataBase(); - - if (weatherLocation == null) { - // Nothing to do. Show error. - final RemoteViews view = this.makeErrorView(appWidgetId); - this.updateWidget(view, appWidgetId); - return; - } - - // TODO: improve this code. Too tired right now... - if (!isRefreshAppWidget) { - RemoteViews view; - - final PermanentStorage store = new PermanentStorage(this.getApplicationContext()); - final Current current = store.getWidgetCurrentData(appWidgetId); - if (current != null) { - // Update UI. - view = this.makeView(current, weatherLocation, appWidgetId); - } else { - // Show error. - view = this.makeErrorView(appWidgetId); - } - this.updateWidget(view, appWidgetId); - } else { - RemoteViews view; - - final Current current = this.getRemoteCurrent(weatherLocation); - if (current != null) { - // Update UI. - view = this.makeView(current, weatherLocation, appWidgetId); - - final PermanentStorage store = new PermanentStorage(this.getApplicationContext()); - store.saveWidgetCurrentData(current, appWidgetId); - } else { - // Show error. - view = this.makeErrorView(appWidgetId); - } - this.updateWidget(view, appWidgetId); - } - } - - public static void deleteWidgetCurrentData(final Context context, final int appWidgetId) { - final PermanentStorage store = new PermanentStorage(context.getApplicationContext()); - - store.removeWidgetCurrentData(appWidgetId); - } - - private Current getRemoteCurrent(final WeatherLocation weatherLocation) { - - final ServiceCurrentParser weatherService = new ServiceCurrentParser(new JPOSCurrentParser()); - final CustomHTTPClient HTTPClient = new CustomHTTPClient( - AndroidHttpClient.newInstance("Android 4.3 WeatherInformation Agent")); - - try { - return this.getRemoteCurrentThrowable(weatherLocation, HTTPClient, weatherService); - - } catch (final JsonParseException e) { - Log.e(TAG, "doInBackground exception: ", e); - } catch (final ClientProtocolException e) { - Log.e(TAG, "doInBackground exception: ", e); - } catch (final MalformedURLException e) { - Log.e(TAG, "doInBackground exception: ", e); - } catch (final URISyntaxException e) { - Log.e(TAG, "doInBackground exception: ", e); - } catch (final IOException e) { - // logger infrastructure swallows UnknownHostException :/ - Log.e(TAG, "doInBackground exception: " + e.getMessage(), e); - } finally { - HTTPClient.close(); - } - - return null; - } - - private Current getRemoteCurrentThrowable(final WeatherLocation weatherLocation, - final CustomHTTPClient HTTPClient, final ServiceCurrentParser weatherService) - throws ClientProtocolException, MalformedURLException, URISyntaxException, - JsonParseException, IOException { - - final String APIVersion = this.getResources().getString(R.string.api_version); - - final String urlAPI = this.getResources().getString(R.string.uri_api_weather_today); - final String url = weatherService.createURIAPICurrent(urlAPI, APIVersion, - weatherLocation.getLatitude(), weatherLocation.getLongitude()); - final String urlWithoutCache = url.concat("&time=" + System.currentTimeMillis()); - final String jsonData = HTTPClient.retrieveDataAsString(new URL(urlWithoutCache)); - - return weatherService.retrieveCurrentFromJPOS(jsonData); - } - - private interface UnitsConversor { - - public double doConversion(final double value); - } - - private RemoteViews makeView(final Current current, final WeatherLocation weatherLocation, final int appWidgetId) { - - // TODO: repeating the same code in Overview, Specific and Current!!! - // 1. Update units of measurement. - - UnitsConversor tempUnitsConversor; - String keyPreference = this.getApplicationContext().getString(R.string.widget_preferences_temperature_units_key); - String realKeyPreference = keyPreference + "_" + appWidgetId; - // What was saved to permanent storage (or default values if it is the first time) - final int tempValue = this.getSharedPreferences("WIDGET_PREFERENCES", Context.MODE_PRIVATE).getInt(realKeyPreference, 0); - final String tempSymbol = this.getResources().getStringArray(R.array.weather_preferences_temperature)[tempValue]; - if (tempValue == 0) { - tempUnitsConversor = new UnitsConversor(){ - - @Override - public double doConversion(final double value) { - return value - 273.15; - } - - }; - } else if (tempValue == 1) { - tempUnitsConversor = new UnitsConversor(){ - - @Override - public double doConversion(final double value) { - return (value * 1.8) - 459.67; - } - - }; - } else { - tempUnitsConversor = new UnitsConversor(){ - - @Override - public double doConversion(final double value) { - return value; - } - - }; - } - - - // 2. Update country. - keyPreference = this.getApplicationContext().getString(R.string.widget_preferences_country_switch_key); - realKeyPreference = keyPreference + "_" + appWidgetId; - // What was saved to permanent storage (or default values if it is the first time) - final boolean isCountry = this.getSharedPreferences("WIDGET_PREFERENCES", Context.MODE_PRIVATE) - .getBoolean(realKeyPreference, false); - - - // 3. Formatters - final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US); - tempFormatter.applyPattern("#####.#####"); - - - // 4. Prepare data for RemoteViews. - String tempMax = ""; - if (current.getMain().getTemp_max() != null) { - double conversion = (Double) current.getMain().getTemp_max(); - conversion = tempUnitsConversor.doConversion(conversion); - tempMax = tempFormatter.format(conversion) + tempSymbol; - } - String tempMin = ""; - if (current.getMain().getTemp_min() != null) { - double conversion = (Double) current.getMain().getTemp_min(); - conversion = tempUnitsConversor.doConversion(conversion); - tempMin = tempFormatter.format(conversion) + tempSymbol; - } - Bitmap picture; - if ((current.getWeather().size() > 0) - && (current.getWeather().get(0).getIcon() != null) - && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) { - final String icon = current.getWeather().get(0).getIcon(); - picture = BitmapFactory.decodeResource(this.getResources(), IconsList.getIcon(icon) - .getResourceDrawable()); - } else { - picture = BitmapFactory.decodeResource(this.getResources(), - R.drawable.weather_severe_alert); - } - final String city = weatherLocation.getCity(); - final String country = weatherLocation.getCountry(); - - // 5. Insert data in RemoteViews. - final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget); - remoteView.setImageViewBitmap(R.id.weather_appwidget_image, picture); - remoteView.setTextViewText(R.id.weather_appwidget_temperature_max, tempMax); - remoteView.setTextViewText(R.id.weather_appwidget_temperature_min, tempMin); - remoteView.setTextViewText(R.id.weather_appwidget_city, city); - if (!isCountry) { - remoteView.setViewVisibility(R.id.weather_appwidget_country, View.GONE); - } else { - // TODO: It is as if Android had a view cache. If I did not set VISIBLE value, - // the country field would be gone forever... :/ - remoteView.setViewVisibility(R.id.weather_appwidget_country, View.VISIBLE); - remoteView.setTextViewText(R.id.weather_appwidget_country, country); - } - - - // 6. Activity launcher. - final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class); - resultIntent.putExtra("actionFromUser", true); - resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); - // resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK ); - // From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget - final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId)); - resultIntent.setData(data); - - final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext()); - // Adds the back stack for the Intent (but not the Intent itself) - stackBuilder.addParentStack(WidgetConfigure.class); - // Adds the Intent that starts the Activity to the top of the stack - stackBuilder.addNextIntent(resultIntent); - final PendingIntent resultPendingIntent = - stackBuilder.getPendingIntent( - 0, - PendingIntent.FLAG_UPDATE_CURRENT - ); - remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent); -// final PendingIntent resultPendingIntent = PendingIntent.getActivity( -// this.getApplicationContext(), -// 0, -// resultIntent, -// PendingIntent.FLAG_UPDATE_CURRENT); -// remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent); - - return remoteView; - } - - private RemoteViews makeErrorView(final int appWidgetId) { - final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(), R.layout.appwidget_error); - - // 6. Activity launcher. - final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class); - resultIntent.putExtra("actionFromUser", true); - resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); -// resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK ); - // From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget - final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/") ,String.valueOf(appWidgetId)); - resultIntent.setData(data); - - final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext()); - // Adds the back stack for the Intent (but not the Intent itself) - stackBuilder.addParentStack(WidgetConfigure.class); - // Adds the Intent that starts the Activity to the top of the stack - stackBuilder.addNextIntent(resultIntent); - final PendingIntent resultPendingIntent = - stackBuilder.getPendingIntent( - 0, - PendingIntent.FLAG_UPDATE_CURRENT - ); - remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent); -// final PendingIntent resultPendingIntent = PendingIntent.getActivity( -// this.getApplicationContext(), -// 0, -// resultIntent, -// PendingIntent.FLAG_UPDATE_CURRENT); -// remoteView.setOnClickPendingIntent(R.id.weather_appwidget_error, resultPendingIntent); - - return remoteView; - } - - private void updateWidget(final RemoteViews remoteView, final int appWidgetId) { - - final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext()); - manager.updateAppWidget(appWidgetId, remoteView); - } - -// private void updateWidgets(final RemoteViews remoteView) { -// -// final ComponentName widgets = new ComponentName(this.getApplicationContext(), WidgetProvider.class); -// final AppWidgetManager manager = AppWidgetManager.getInstance(this.getApplicationContext()); -// manager.updateAppWidget(widgets, remoteView); -// } -}