Skip to content

Commit

Permalink
Auto detect location implementation, added preference for auto detect…
Browse files Browse the repository at this point in the history
…ion.
  • Loading branch information
uxcam-mobile committed Jan 28, 2016
1 parent a6e6709 commit 32ef745
Show file tree
Hide file tree
Showing 7 changed files with 178 additions and 12 deletions.
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ dependencies {
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.google.android.apps.dashclock:dashclock-api:+'
compile 'com.google.android.gms:play-services-location:8.4.0'
}
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,5 @@

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>
4 changes: 2 additions & 2 deletions app/src/main/java/cz/martykan/forecastie/AlarmReceiver.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ protected Void doInBackground(String... params) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String language = Locale.getDefault().getLanguage();
if(language.equals("cs")) { language = "cz"; }
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + URLEncoder.encode(sp.getString("city", "London"), "UTF-8") + "&lang="+ language +"&appid=78dfe9e10dd180fadd805075dd1a10d6");
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + URLEncoder.encode(sp.getString("city", Constants.DEFAULT_CITY), "UTF-8") + "&lang="+ language +"&appid=78dfe9e10dd180fadd805075dd1a10d6");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

Expand Down Expand Up @@ -90,7 +90,7 @@ protected Void doInBackground(String... params) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String language = Locale.getDefault().getLanguage();
if(language.equals("cs")) { language = "cz"; }
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?q=" + URLEncoder.encode(sp.getString("city", "London"), "UTF-8") + "&lang="+ language +"&mode=json&appid=78dfe9e10dd180fadd805075dd1a10d6");
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?q=" + URLEncoder.encode(sp.getString("city", Constants.DEFAULT_CITY), "UTF-8") + "&lang="+ language +"&mode=json&appid=78dfe9e10dd180fadd805075dd1a10d6");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

Expand Down
7 changes: 7 additions & 0 deletions app/src/main/java/cz/martykan/forecastie/Constants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package cz.martykan.forecastie;

public class Constants {
public static final String DEFAULT_CITY = "London";
public static final String DEFAULT_LAT = "51.5072";
public static final String DEFAULT_LON = "0.1275";
}
170 changes: 160 additions & 10 deletions app/src/main/java/cz/martykan/forecastie/MainActivity.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
package cz.martykan.forecastie;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
Expand All @@ -30,6 +35,10 @@
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
Expand All @@ -45,7 +54,9 @@
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;
Typeface weatherFont;
Weather todayWeather = new Weather();

Expand All @@ -69,6 +80,8 @@ public class MainActivity extends AppCompatActivity {
private List<Weather> longTermTodayWeather;
private List<Weather> longTermTomorrowWeather;

GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
darkTheme = false;
Expand Down Expand Up @@ -116,6 +129,103 @@ protected void onCreate(Bundle savedInstanceState) {

// Set autoupdater
setRecurringAlarm(this);

// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_ACCESS_COARSE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay!
onConnectedTask();

} else {

// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}

// other 'case' lines to check for other
// permissions this app might request
}
}

@Override
public void onConnected(Bundle connectionHint) {
onConnectedTask();
}

private void onConnectedTask() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {

// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Provide Location Permission")
.setMessage("Require Location permission to access your location")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();

} else {

// No explanation needed, we can request the permission.

ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_ACCESS_COARSE_LOCATION);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
return;
}
Log.d("MainActivity", "Got Location");
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
String lat = String.valueOf(mLastLocation.getLatitude());
String lon = String.valueOf(mLastLocation.getLongitude());
saveLocation(lat, lon);
}
}


@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("MainActivity", "Connection Failed");
}

@Override
public void onConnectionSuspended(int i) {
Log.d("MainActivity", "suspended "+i);
}

public WeatherRecyclerAdapter getAdapter(int id){
Expand Down Expand Up @@ -208,11 +318,7 @@ public void onClick(DialogInterface dialog, int whichButton) {
if (result.matches("")) {

} else {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("city", result);
editor.commit();
getTodayWeather();
getLongTermWeather();
saveLocation(result);
}
}
});
Expand All @@ -224,6 +330,23 @@ public void onClick(DialogInterface dialog, int whichButton) {
alert.show();
}

private void saveLocation(String result) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("city", result);
editor.commit();
getTodayWeather();
getLongTermWeather();
}

private void saveLocation(String lat, String lon) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lat", lat);
editor.putString("lon", lon);
editor.commit();
getTodayWeather();
getLongTermWeather();
}

private void aboutDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Forecastie");
Expand Down Expand Up @@ -453,6 +576,18 @@ public boolean onCreateOptionsMenu(Menu menu) {
return true;
}

@Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}

@Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Expand Down Expand Up @@ -483,7 +618,7 @@ public class GetWeatherTask extends AsyncTask<String, String, Void> {
protected void onPreExecute() {
loading = 1;
if(!progressDialog.isShowing()) {
progressDialog.setMessage("Downloading your data...");
progressDialog.setMessage(getString(R.string.downloading_data));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
Expand All @@ -497,7 +632,14 @@ protected Void doInBackground(String... params) {
if (language.equals("cs")) {
language = "cz";
}
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + URLEncoder.encode(sp.getString("city", "London"), "UTF-8") + "&lang=" + language + "&appid=78dfe9e10dd180fadd805075dd1a10d6");
boolean autoDetectLocation = sp.getBoolean("autoDetectLocation", true);
URL url;
if (sp.getString("lat", "abc").equals("abc") || !autoDetectLocation) {
url = new URL("http://api.openweathermap.org/data/2.5/weather?q=" + URLEncoder.encode(sp.getString("city", Constants.DEFAULT_CITY), "UTF-8") + "&lang=" + language + "&appid=78dfe9e10dd180fadd805075dd1a10d6");
} else {
url = new URL("http://api.openweathermap.org/data/2.5/weather?" +
"lat=" + sp.getString("lat", Constants.DEFAULT_LAT) +"&lon="+sp.getString("lon", Constants.DEFAULT_LON)+ "&lang=" + language + "&appid=78dfe9e10dd180fadd805075dd1a10d6");
}
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

Expand Down Expand Up @@ -533,7 +675,7 @@ class GetLongTermWeatherTask extends AsyncTask<String, String, Void> {
protected void onPreExecute() {
loading += 1;
if(!progressDialog.isShowing()) {
progressDialog.setMessage("Downloading your data...");
progressDialog.setMessage(getString(R.string.downloading_data));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
Expand All @@ -547,7 +689,15 @@ protected Void doInBackground(String... params) {
if (language.equals("cs")) {
language = "cz";
}
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast?q=" + URLEncoder.encode(sp.getString("city", "London"), "UTF-8") + "&lang=" + language + "&mode=json&appid=78dfe9e10dd180fadd805075dd1a10d6");

boolean autoDetectLocation = sp.getBoolean("autoDetectLocation", true);
URL url;
if (sp.getString("lat", "abc").equals("abc") || !autoDetectLocation) {
url = new URL("http://api.openweathermap.org/data/2.5/forecast?q=" + URLEncoder.encode(sp.getString("city", Constants.DEFAULT_CITY), "UTF-8") + "&lang=" + language + "&mode=json&appid=78dfe9e10dd180fadd805075dd1a10d6");
}else{
url = new URL("http://api.openweathermap.org/data/2.5/forecast?" +
"lat=" + sp.getString("lat", Constants.DEFAULT_LAT) +"&lon="+sp.getString("lon", Constants.DEFAULT_LON)+ "&lang=" + language + "&mode=json&appid=78dfe9e10dd180fadd805075dd1a10d6");
}
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<string name="humidity">Humidity</string>

<string name="search_title">Search for city</string>
<string name="downloading_data">Downloading your data ...</string>

<string name="error_dateFormat">DATE FORMAT ERROR</string>

Expand All @@ -25,6 +26,7 @@
<string name="setting_tempUnits">Temperature units</string>
<string name="setting_pressureUnits">Pressure units</string>
<string name="setting_darkTheme">Dark theme</string>
<string name="setting_auto_detect_location">Detect Location</string>
<string name="setting_differentiateDaysByTint">Differentiate Days with Color</string>
<string name="setting_refreshInterval">Background refresh interval</string>

Expand Down
5 changes: 5 additions & 0 deletions app/src/main/res/xml/prefs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,10 @@
android:defaultValue="false"
android:key="differentiateDaysByTint"
android:title="@string/setting_differentiateDaysByTint" />

<CheckBoxPreference
android:defaultValue="true"
android:key="autoDetectLocation"
android:title="@string/setting_auto_detect_location" />
</PreferenceCategory>
</PreferenceScreen>

1 comment on commit 32ef745

@martykan
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic is good, but Google Play Services are proprietary software, thus they cannot be used. I will change it to use native location servives.

Please sign in to comment.