Skip to content

Instantly share code, notes, and snippets.

@judeebene
Created April 30, 2018 10:06
Show Gist options
  • Save judeebene/8134b07cb2784cb413edab5fec396094 to your computer and use it in GitHub Desktop.
Save judeebene/8134b07cb2784cb413edab5fec396094 to your computer and use it in GitHub Desktop.
package com.shareqube.nammi.service;
import android.Manifest;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.shareqube.nammi.R;
import com.shareqube.nammi.util.Constants;
import com.shareqube.nammi.model.UserLocation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Created by judeebene on 7/28/16.
*/
public class IbomLocationService extends IntentService {
public static String LOG_TAG = IbomLocationService.class.getSimpleName();
//// TODO: 10/13/16 to Update Location service to current location instead of last location
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private LocationListener mLocationListener;
LocationManager mLocationManager;
FirebaseUser currentUser;
DatabaseReference database;
DatabaseReference guestLocationRef;
SharedPreferences initialUserLocationUpdatePref;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public IbomLocationService(String name) {
super(name);
}
public IbomLocationService(){
super("");
}
@Override
public void onCreate() {
super.onCreate();
currentUser = FirebaseAuth.getInstance().getCurrentUser();
database = FirebaseDatabase.getInstance().getReference();
guestLocationRef = database.child(Constants.FIREBASE_USER_LOCATION);
Log.e(LOG_TAG, guestLocationRef.getRef().toString());
}
@Override
protected void onHandleIntent(Intent mIntent) {
initialUserLocationUpdatePref = getSharedPreferences(Constants.INITIAL_USER_LOCATION_PREF, 3);
//// TODO: 10/13/16 Remember to broadcast the location for notification
Log.e(LOG_TAG, "Intent firing....." + mIntent);
if (LocationResult.hasResult(mIntent)) {
LocationResult locationResult = LocationResult.extractResult(mIntent);
Location mlocation = locationResult.getLastLocation();
Log.e(LOG_TAG, " there is an intent");
if (null != mlocation) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Log.e(LOG_TAG, "location Manager" + mLocationManager);
Criteria criteria = new Criteria();
String bestProvider = mLocationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
final Location lastKnownLocation = mLocationManager.getLastKnownLocation(bestProvider);
Double lat = (lastKnownLocation == null) ? mlocation.getLatitude() : lastKnownLocation.getLatitude();
Double longi = (lastKnownLocation == null) ? mlocation.getLongitude() : lastKnownLocation.getLongitude();
List<Address> addresses = getAddress(lat, longi);
if (addresses != null) {
updateAddressLocation(addresses);
}
}
} else {
Log.e(LOG_TAG, " has No location Intent");
}
}
public List<Address> getAddress(double latitude, double longitude) {
Geocoder gcd = new Geocoder(IbomLocationService.this, Locale.getDefault());
List<Address> addresses = null;
if (!Geocoder.isPresent()) {
Log.e(LOG_TAG, " Geo coder is not present ");
//getAddress(latitude , longitude);
gcd = new Geocoder(IbomLocationService.this, Locale.getDefault());
}
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
return addresses;
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG, "Fom exception" + e.getMessage());
AddressTask addressTask = new AddressTask();
addressTask.execute(new LatLng(latitude, longitude));
}
// if address is null, then use the server Geo Location REST API
return addresses;
}
//inner class to get the address from server
class AddressTask extends AsyncTask<LatLng, Void, List<Address>> {
@Override
protected void onPostExecute(List<Address> addresses) {
super.onPostExecute(addresses);
if(addresses !=null) {
updateAddressLocation(addresses);
}
}
@Override
protected List<Address> doInBackground(LatLng... latLngs) {
List<Address> addressReturn = null;
try {
final String BASE_URL = " https://maps.googleapis.com/maps/api/geocode/json?";
final String LATLNG_PARAM = "latlng";
final String KEY_PARAM = "Key";
LatLng userLatlng = latLngs[0];
String latlngStr = userLatlng.latitude + "," + userLatlng.longitude;
Uri buildUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(LATLNG_PARAM, latlngStr)
.appendQueryParameter(KEY_PARAM, getApplicationContext().getResources().getString(R.string.geo_coding_server_key))
.build();
URL url = new URL(buildUri.toString());
Log.e(LOG_TAG, "Built URL" + buildUri.toString());
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
switch (urlConnection.getResponseCode()) {
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
Toast.makeText(IbomLocationService.this ,"Network time out" , Toast.LENGTH_LONG).show();
return null ;
// retry
case HttpURLConnection.HTTP_UNAVAILABLE:
Toast.makeText(IbomLocationService.this ,"Network not available" , Toast.LENGTH_LONG).show();
return null;
// retry, server is unstable
default:
break ;
}
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String addressJsonStr = buffer.toString();
Log.e(LOG_TAG, "Json Addess" + addressJsonStr);
try {
addressReturn = getAdressJson(addressJsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
//end
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
}
Log.e(LOG_TAG, "ADDRESS RETURN" + addressReturn);
return addressReturn;
}
}
// get the json data
public List<Address> getAdressJson(String jsonStr) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonStr);
ArrayList retList = new ArrayList<Address>();
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
if (results.length() > 0) {
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
Address addr = new Address(Locale.getDefault());
// addr.setAddressLine(0, result.getString("formatted_address"));
JSONArray components = result.getJSONArray("address_components");
String streetNumber = "";
String route = "";
for (int a = 0; a < components.length(); a++) {
JSONObject component = components.getJSONObject(a);
JSONArray types = component.getJSONArray("types");
for (int j = 0; j < types.length(); j++) {
String type = types.getString(j);
if (type.equals("locality")) {
addr.setLocality(component.getString("long_name"));
} else if (type.equals("administrative_area_level_1")) {
addr.setAdminArea(component.getString("long_name"));
} else if (type.equals("country")) {
addr.setCountryName(component.getString("long_name"));
} else if (type.equals("street_number")) {
streetNumber = component.getString("long_name");
} else if (type.equals("route")) {
route = component.getString("long_name");
}
}
}
addr.setAddressLine(0, route + " " + streetNumber);
addr.setLatitude(result.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
addr.setLongitude(result.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
retList.add(addr);
}
return retList;
}
}
return retList;
}
public void updateAddressLocation(List<Address> addressUpdate) {
if (addressUpdate != null && addressUpdate.size() > 0) {
String cityName = addressUpdate.get(0).getLocality();
String countryName = addressUpdate.get(0).getCountryName();
String stateName = addressUpdate.get(0).getAdminArea();
String address = addressUpdate.get(0).getAddressLine(0);
Double addressLatitude = addressUpdate.get(0).getLatitude();
Double addressLongitude = addressUpdate.get(0).getLongitude();
// update guest location
HashMap<String, Object> guestLocation = new HashMap<String, Object>();
UserLocation userLocation = new UserLocation(addressLatitude, addressLongitude, address, cityName, stateName, countryName);
Map<String, Object> guestLocationMap = userLocation.toMap();
/* Add the user and UID to the update map */
guestLocation.put("/", guestLocationMap);
/* Try to update the database; if there is already a guest, this will fail */
guestLocationRef.child(currentUser.getUid()).setValue(userLocation, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Log.e(LOG_TAG , "user location updated");
initialUserLocationUpdatePref.edit().
putBoolean(Constants.INITIAL_USER_LOCATION_EXTRA, true).apply();
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment