Skip to content

Commit

Permalink
Integrate LocationPreference with sun mode
Browse files Browse the repository at this point in the history
See #29

The location is now updated silently when:
* The user selects the sun mode
* The filter is automatically turned on or off

Furthermore the location is explicitly updated when the user taps the
LocationPreference.

The AutomaticFilterChangeReceiver has been simplified, since it doesn't
have to find the sunset nor a location anymore, but just reads the
current on and off times. The on and off times are saved in the keys off
the new FilterTimePreferences. They change to sunrise and sunset times
when the sun mode is selected, automatically backing up the custom
times.

When the location fails to update when it has been explicitly called by
the user, a toast with a notice is displayed.

When the user selects the sun mode with a unset location, sensible
default sunrise and sunset values are set as turn on and off times.
  • Loading branch information
raatmarien committed Apr 5, 2016
1 parent f251f8d commit fe15b6e
Show file tree
Hide file tree
Showing 9 changed files with 426 additions and 170 deletions.
104 changes: 80 additions & 24 deletions app/src/main/java/com/jmstudios/redmoon/fragment/ShadesFragment.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,13 @@
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.location.Location;
import android.location.LocationManager;

import com.jmstudios.redmoon.R;
import com.jmstudios.redmoon.presenter.ShadesPresenter;
import com.jmstudios.redmoon.activity.ShadesActivity;
import com.jmstudios.redmoon.preference.TimePickerPreference;
import com.jmstudios.redmoon.preference.FilterTimePreference;
import com.jmstudios.redmoon.preference.LocationPreference;

public class ShadesFragment extends PreferenceFragment {
Expand All @@ -75,8 +77,8 @@ public class ShadesFragment extends PreferenceFragment {
private SwitchPreference darkThemePref;
private CheckBoxPreference lowerBrightnessPref;
private ListPreference automaticFilterPref;
private TimePickerPreference automaticTurnOnPref;
private TimePickerPreference automaticTurnOffPref;
private FilterTimePreference automaticTurnOnPref;
private FilterTimePreference automaticTurnOffPref;
private LocationPreference locationPref;

private boolean searchingLocation;
Expand All @@ -102,8 +104,8 @@ public void onCreate(Bundle savedInstanceState) {
darkThemePref = (SwitchPreference) prefScreen.findPreference(darkThemePrefKey);
lowerBrightnessPref = (CheckBoxPreference) prefScreen.findPreference(lowerBrightnessPrefKey);
automaticFilterPref = (ListPreference) prefScreen.findPreference(automaticFilterPrefKey);
automaticTurnOnPref = (TimePickerPreference) prefScreen.findPreference(automaticTurnOnPrefKey);
automaticTurnOffPref = (TimePickerPreference) prefScreen.findPreference(automaticTurnOffPrefKey);
automaticTurnOnPref = (FilterTimePreference) prefScreen.findPreference(automaticTurnOnPrefKey);
automaticTurnOffPref = (FilterTimePreference) prefScreen.findPreference(automaticTurnOffPrefKey);
locationPref = (LocationPreference) prefScreen.findPreference(locationPrefKey);

darkThemePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
Expand Down Expand Up @@ -143,31 +145,85 @@ public boolean onPreferenceChange(Preference preference, Object newValue) {

automaticFilterPref.setSummary(automaticFilterPref.getEntry());

onAutomaticFilterPreferenceChange(automaticFilterPref,
automaticFilterPref.getValue().toString());

automaticFilterPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean custom = newValue.toString().equals("custom");
automaticTurnOnPref.setEnabled(custom);
automaticTurnOffPref.setEnabled(custom);

boolean sun = newValue.toString().equals("sun");
locationPref.setEnabled(sun);

if (newValue.toString().equals("sun") && ContextCompat.checkSelfPermission
(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
return false;
}

ListPreference lp = (ListPreference) preference;
String entry = lp.getEntries()[lp.findIndexOfValue(newValue.toString())].toString();
lp.setSummary(entry);
return onAutomaticFilterPreferenceChange(preference, newValue);
}
});

return true;
locationPref.setOnLocationChangedListener(new LocationPreference.OnLocationChangedListener() {
@Override
public void onLocationChange() {
if (automaticFilterPref.getValue().equals("sun")) {
updateFilterTimesFromSun();
}
}
});

}

private boolean onAutomaticFilterPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("sun") && ContextCompat.checkSelfPermission
(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
return false;
}

boolean custom = newValue.toString().equals("custom");
automaticTurnOnPref.setEnabled(custom);
automaticTurnOffPref.setEnabled(custom);

boolean sun = newValue.toString().equals("sun");
locationPref.setEnabled(sun);

// From something to sun
if (newValue.toString().equals("sun")) {
// Update the FilterTimePreferences
updateFilterTimesFromSun();

// Attempt to get a new location
locationPref.searchLocation(false);
}

// From sun to something
String oldValue = preference.getSharedPreferences().getString
(preference.getKey(), "never");
if (oldValue.equals("sun") && !newValue.equals("sun")) {
automaticTurnOnPref.setToCustomTime();
automaticTurnOffPref.setToCustomTime();
}

ListPreference lp = (ListPreference) preference;
String entry = lp.getEntries()[lp.findIndexOfValue(newValue.toString())].toString();
lp.setSummary(entry);

return true;
}

private void updateFilterTimesFromSun() {
String location = locationPref.getLocation();
if (location.equals("not set")) {
automaticTurnOnPref.setToSunTime("19:30");
automaticTurnOffPref.setToSunTime("06:30");
} else {
Location androidLocation = new Location(LocationManager.NETWORK_PROVIDER);
androidLocation.setLatitude(Double.parseDouble(location.split(",")[0]));
androidLocation.setLongitude(Double.parseDouble(location.split(",")[1]));

String sunsetTime = FilterTimePreference.getSunTimeFromLocation
(androidLocation, true);
automaticTurnOnPref.setToSunTime(sunsetTime);

String sunriseTime = FilterTimePreference.getSunTimeFromLocation
(androidLocation, false);
automaticTurnOffPref.setToSunTime(sunriseTime);
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Copyright (c) 2016 Marien Raat <marienraat@riseup.net>
*
* This file is free software: you may copy, redistribute and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This file is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jmstudios.redmoon.preference;

import android.content.Context;
import android.util.AttributeSet;
import android.content.SharedPreferences;

import java.util.TimeZone;
import java.util.Calendar;

import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;

import com.jmstudios.redmoon.preference.TimePickerPreference;

public class FilterTimePreference extends TimePickerPreference {
public static final String TAG = "FilterTimePreference";
public static final boolean DEBUG = true;

private boolean mIsCustom = true;

public FilterTimePreference(Context context, AttributeSet attrs) {
super(context, attrs);
}

public void setToSunTime(String time) {
if (mIsCustom) {
// Backup custom times
SharedPreferences.Editor editor = getSharedPreferences().edit();
editor.putString(getKey() + "_custom", mTime);
editor.commit();
}
mTime = time;
persistString(mTime);
setSummary(mTime);

mIsCustom = false;
}

public void setToCustomTime() {
mIsCustom = true;

mTime = getSharedPreferences().getString(getKey() + "_custom", DEFAULT_VALUE);
persistString(mTime);
setSummary(mTime);
}

public static String getSunTimeFromLocation(android.location.Location location,
boolean sunset) {
com.luckycatlabs.sunrisesunset.dto.Location sunriseSunsetLocation =
new com.luckycatlabs.sunrisesunset.dto.Location(location.getLatitude(),
location.getLongitude());
SunriseSunsetCalculator calculator = new SunriseSunsetCalculator
(sunriseSunsetLocation, TimeZone.getDefault());
if (sunset) {
return calculator.getOfficialSunsetForDate(Calendar.getInstance());
} else {
return calculator.getOfficialSunriseForDate(Calendar.getInstance());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Copyright (c) 2016 Marien Raat <marienraat@riseup.net>
*
* This file is free software: you may copy, redistribute and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This file is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jmstudios.redmoon.preference;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.util.Log;
import android.widget.Toast;

import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;

import com.jmstudios.redmoon.receiver.LocationUpdateListener;

import com.jmstudios.redmoon.R;

public class LocationPreference extends Preference {
private static final String TAG = "LocationPreference";
private static final boolean DEBUG = true;

public static final String DEFAULT_VALUE = "not set";

// Location in the form "$LAT,$LONG"
private String mLocation;

private Context mContext;
private boolean mIsSearchingLocation;
private boolean mIsSearchExplicit;

private OnLocationChangedListener mLocationChangeListener;

public LocationPreference(Context context, AttributeSet attrs) {
super(context, attrs);

mContext = context;
mIsSearchingLocation = false;
}

public String getLocation() {
return mLocation;
}

public void setOnLocationChangedListener(OnLocationChangedListener listener) {
mLocationChangeListener = listener;
}

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}

@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
mLocation = getPersistedString(DEFAULT_VALUE);
} else {
mLocation = defaultValue.toString();
persistString(mLocation);
}
if (DEBUG) Log.i(TAG, "LocationPreference set to: " + mLocation);

updateSummary();
}

@Override
protected void onBindView(View view) {
super.onBindView(view);
}

@Override
protected void onClick() {
searchLocation(true);
}

private void updateSummary() {
if (mLocation.equals("not set")) {
setSummary(mContext.getString(R.string.location_not_set));
} else {
String shortLatitude = mContext.getString(R.string.latitude_short);
String shortLongitude = mContext.getString(R.string.longitude_short);

double latitude = Double.parseDouble
(mLocation.substring(0, mLocation.indexOf(",")));
double longitude = Double.parseDouble
(mLocation.substring(mLocation.indexOf(",") + 1, mLocation.length()));

String summary = String.format("%s: %.2f %s: %.2f",
shortLatitude, latitude,
shortLongitude, longitude);
setSummary(summary);
}
}

public void searchLocation(boolean explicitRequest) {
if (mIsSearchingLocation)
mIsSearchExplicit = explicitRequest || mIsSearchExplicit;
else
mIsSearchExplicit = explicitRequest;
if (!mIsSearchingLocation) {
if (DEBUG) Log.i(TAG, explicitRequest ?
"Searching location on explicit request" :
"Searching location automatically");
mIsSearchingLocation = true;

LocationManager locationManager = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
LocationListener listener = new LocationUpdateListener(mContext, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, listener);
} else {
handleLocationSearchFailed();
}
}

if (mIsSearchExplicit && mIsSearchingLocation) {
setSummary(mContext.getString(R.string.searching_location));
}
}

public void handleLocationFound(Location location) {
mIsSearchingLocation = false;

mLocation = location.getLatitude() + "," + location.getLongitude();
persistString(mLocation);
updateSummary();

if (mLocationChangeListener != null)
mLocationChangeListener.onLocationChange();
}

public void handleLocationSearchFailed() {
mIsSearchingLocation = false;

if (mIsSearchExplicit) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText
(mContext, mContext.getString
(R.string.toast_warning_no_location), duration);
toast.show();
}

updateSummary();
}

// LocationChangedListener
public interface OnLocationChangedListener {
public abstract void onLocationChange();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public class TimePickerPreference extends DialogPreference {
private static final boolean DEBUG = true;

private TimePicker mTimePicker;
private String mTime;
protected String mTime;

public TimePickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
Expand Down

0 comments on commit fe15b6e

Please sign in to comment.