I'm doing a project where i need to get the gps location when an anomaly occurs.
How i call/start the gps location in a method inside my Anomaly class?
So i have a class Anomaly and i've used this class to get the gps location:
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
public class GPS extends Activity {
private LocationManager locationManager;
private LocationListener locationListener;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append("\n "+location.getLatitude()+" "+location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
}
}else {
updateGPS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 10:
if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED)
updateGPS();
}
}
public void updateGPS() {
locationManager.requestLocationUpdates("gps", 3600000, 0, locationListener);
}
}
this is my class Anormaly (i'm a begginer so i don´t know what i should extend and if i need to start a new intent)
public class Anomaly extends AppCompatActivity{
private GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
}
public void abnormalHRDetected(int heartRateInt) {
if (heartRateInt < 40 || heartRateInt > 120) {
Intent intent = new Intent(this, GPS.class);
startActivity(intent);
finish();
}
}
It's simple. I'm receiving the heart rate and i put that on a screen "data". When the value of the heart rate it's lower than 40 or bigger than 120 occurs an anomaly and i want get the gps location at the moment (to send to a data base not to put that on the screen) sorry about my english
Make sure you should give access_gps and access_finelocation permissions in your manifest file.
The below code may help you to fix your problem
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
public class GPS extends Activity {
private LocationManager locationManager;
private LocationListener locationListener;
private TextView textView;
Location cLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
}
}else {
cLocation = updateGPS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 10:
if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED)
cLocation = updateGPS(); //In update gps method the textview will set to current lat & long values and it returns the current location to your cLocation variable, if you wana use that values further you can use with cLocation variable.
}
}
public Location updateGPS() {
Location currentLocation;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append("\n "+location.getLatitude()+" "+location.getLongitude());
currentLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
locationManager.requestLocationUpdates("gps", 3600000, 0, locationListener);
}
return currentLocation;
}
}
Refer this link
https://github.com/HariKrish4/TurnNavigation
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Location;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 100;
private GoogleMap mMap;
ArrayList<LatLng> list = new ArrayList<>();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getDirections();
}
private void getDirections() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=triplicane,chennai&destination=saidapet,chennai&sensor=false";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
try {
JSONObject json = new JSONObject(response);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
list = decodePoly(encodedString);
// Polylines are useful for marking paths and routes on the map.
mMap.addPolyline(new PolylineOptions().geodesic(true)
.addAll(list)
);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
} else {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
putNavigationMarker();
createLocationRequest();
startLocationUpdates();
}
}
private void startLocationUpdates() {
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;
}else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private void putNavigationMarker() {
LatLng mapCenter = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mapCenter, 13));
// Flat markers will rotate when the map is rotated,
// and change perspective when the map is tilted.
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_navigation_black_48dp))
.position(mapCenter)
.flat(true)
.rotation(245));
CameraPosition cameraPosition = CameraPosition.builder()
.target(mapCenter)
.zoom(16)
.bearing(90)
.build();
// Animate the change in camera view over 2 seconds
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
2000, null);
}
public void animateMarker(final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_ACCESS_FINE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
putNavigationMarker();
} else {
// permission denied
finish();
}
break;
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng mapCenter = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
animateMarker(marker,mapCenter,false);
}
}
I suggest to use the code below, use the interface LocationListener like a parameter. That way you don´t need to start Activity to get Location as in the original code.
Make sure you give ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION and ACCESS_NETWORK_STATE permissions on your manifest file.
public class LocationSuporte
{
private LocationListener mLocationListener;
private final static String TAG = "Location Suporte";
private Context mContext;
public LocationSuporte(Context mContext, LocationListener mLocationListener) {
this.mLocationListener = mLocationListener;
this.mContext = mContext;
}
public boolean isGPSEnable() {
LocationManager lManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
return lManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || lManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public boolean isNetworkAvailable() {
final ConnectivityManager connectivityManager = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
public Location getLocation() {
Location location = null;
LocationManager lManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
return null;
}
try {
boolean isGPSEnabled = this.isGPSEnable();
Log.d(TAG, "isGPSEnabled = " + isGPSEnabled);
boolean isNetworkEnabled = isNetworkAvailable();
Log.d(TAG, "isNetworkEnabled = " + isNetworkEnabled);
if (isNetworkEnabled) {
lManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this.mLocationListener);
if (lManager != null) {
location = lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled && location == null) {
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this.mLocationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (lManager != null) {
location = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
} catch (Exception e) {
e.printStackTrace();
}
lManager.removeUpdates(this.mLocationListener);
return location;
}
}
Use example;
public void abnormalHRDetected(int heartRateInt)
{
if (heartRateInt < 40 || heartRateInt > 120) {
Location location = new LocationSuporte(getApplicationContext(), new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("EXAMPLE","onLocationChanged");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("EXAMPLE","onStatusChanged");
}
#Override
public void onProviderEnabled(String s) {
Log.d("EXAMPLE","onProviderEnabled");
}
#Override
public void onProviderDisabled(String s) {
Log.d("EXAMPLE","onProviderDisabled");
}
}).getLocation();
Log.d("EXAMPLE","\n "+location.getLatitude()+" "+location.getLongitude());
}
}
Related
I want to detect when wifi is disabled all the time. When the user disables the wifi, I want to call openWifiWindow() method in order to prompt user to enable it again. After going back, gps should find the location again. How can I achieve this in my code?
This is my code
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 16f;
public Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
getLocationPermission();
}
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionsGranted) {
getDeviceLocation();
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//map is ready
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
//mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation() {
// getting the device's current location
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (mLocationPermissionsGranted) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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 Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
//onComplete: found location
Location currentLocation = (Location) task.getResult();
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
//Finding user's location
LatLng myCoordinates = new LatLng(latitude, longitude);
moveCamera(myCoordinates, DEFAULT_ZOOM);
//Adding an icon marker to display the user's location and the info window from above
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();
} else {
//unable to get current location
}
}
});
}
}
private void moveCamera(LatLng latLng, float zoom) {
//moveCamera: moving the camera to: lat: + latLng.latitude + lng: + latLng.longitude
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
}
}
}
updateLocationUI();
}
public void openWifiWindow() {
Intent intent = new Intent(this, EnableWifiWindow.class);
startActivity(intent);
}
}
You have two possible solutions, either you can use broadcast receiver to know when wifi turned on/of.
or
you can just check wifi periodically like this. This code goes inside your current activity.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (!CheckWifi()) {
timer.cancel();
/open wifi dialog
}
}
}, 0, 5000);
After asking the user for location permissions and accepts, it doesn't find the location, I have to go back and again inside the app in order to show my location. How can I achieve after giving location permissions to get my location instantly?
This is my code
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 16f;
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Gets the device's current location
getLocationPermission();
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// openGpsWindow();
//}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//map is ready
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation() {
// getting the device's current location
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (mLocationPermissionsGranted) {
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 Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
//onComplete: found location
Location currentLocation = (Location) task.getResult();
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
//Finding user's location
LatLng myCoordinates = new LatLng(latitude, longitude);
moveCamera(myCoordinates, DEFAULT_ZOOM);
//Adding an icon marker to display the user's location and the info window from above
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();
}else{
//unable to get current location
}
}
});
}
}
private void moveCamera(LatLng latLng, float zoom) {
//moveCamera: moving the camera to: lat: + latLng.latitude + lng: + latLng.longitude
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap() {
//initializing map
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission() {
//getting location permissions
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//onRequestPermissionsResult: called
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
//onRequestPermissionsResult: permission failed
return;
}
}
//onRequestPermissionsResult: permission granted
mLocationPermissionsGranted = true;
//initialize the map
initMap();
}
}
}
}
public void openGpsWindow() {
Intent intent = new Intent(this, EnableGpsWindow.class);
startActivity(intent);
}
}
2)And then If I disable gps while I am in mapsactivity i want to call openGpsWindow(which prompts user to go open the gps again.) Thanks in advance.
You can create a method that updates the UI with the location after the permission has been granted. For example:
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
and then call that method after your initMap() method after the permission has been granted.
If that does not work, you can look here https://github.com/PabiMoloi/Location/blob/master/app/src/main/java/com/example/pmoloi/location/presentation/map/MapsActivity.java , it is a project i created that uses maps.
I want to detect when gps is disabled. When the user disables the gps, I want to call openGpsWindow() in order to prompt user to enable it again. After going back, gps should find the location again. How can i achieve this in my code? Thanks in advance!
My code:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 16f;
public Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
getLocationPermission();
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// openGpsWindow();
//}
}
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionsGranted) {
getDeviceLocation();
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//map is ready
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
//mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation() {
// getting the device's current location
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (mLocationPermissionsGranted) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_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 Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
//onComplete: found location
Location currentLocation = (Location) task.getResult();
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
//Finding user's location
LatLng myCoordinates = new LatLng(latitude, longitude);
moveCamera(myCoordinates, DEFAULT_ZOOM);
//Adding an icon marker to display the user's location and the info window from above
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();
} else {
//unable to get current location
}
}
});
}
}
private void moveCamera(LatLng latLng, float zoom) {
//moveCamera: moving the camera to: lat: + latLng.latitude + lng: + latLng.longitude
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
}
}
}
updateLocationUI();
}
public void openGpsWindow() {
Intent intent = new Intent(this, EnableGpsWindow.class);
startActivity(intent);
}
}
I want to detect when gps is disabled. When the user disables the gps, I want to call openGpsWindow() in order to prompt user to enable it again. After going back, gps should find the location again. How can i achieve this in my code?
Thanks in advance!
You have to implement your MapsActvity with LocationListener along with OnMapReadyCallback. There You will find two override methods of Location Listener.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,LocationListener
Then Just Press Alt+Enter , These Override methods will be automatically added.
#Override
public void onProviderDisabled(String provider) {
Log.e("Location Tag", "Provider Disabled");
openGpsWindow();
}
#Override
public void onProviderEnabled(String provider) {
Log.e("Location Tag", "Provider Enabled");
}
In my Android project I need that when the vehicle is moving, the marker position should also move smoothly, but when location is changed, the marker is jumping from one position to another, it is not moving smoothly.
I searched a lot, but did not get the result.
I do not know what the best way is. Please give me full guidance.
thank you very much
Update
#AnkitMehta thank you for answer
all code in MapsActivity:
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.location.Location;
import android.os.Build;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onPause() {
super.onPause();
//stop Location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("LOG" , "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("LOG", "Can't find style. Error: ", e);
}
//initialize Google play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
// Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
//mLocationRequest.setInterval(30000);
//mLocationRequest.setFastestInterval(30000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
animateMarker(latLng, latLng, true);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation 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("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
//This methos is used to move the marker of each car smoothly when there are any updates of their position
public void animateMarker(final LatLng startPosition, final LatLng toPosition,
final boolean hideMarker) {
final Marker marker = mMap.addMarker(new MarkerOptions()
.position(startPosition)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * toPosition.longitude + (1 - t)
* startPosition.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startPosition.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng)
.build();
CameraUpdate cu = CameraUpdateFactory.newCameraPosition(cameraPosition);
map.animateCamera(cu);
this will move to the latlng selected with animation(Camera position
and camera update is used)
Override this method :
#Override
public void onLocationChange(Location location) {
LatLng latLng = new LatLng(location.latitude, location.longitude);
refreshMapPosition(latLng, 45)
}
private void refreshMapPosition(LatLng pos, float angle) {
CameraPosition.Builder positionBuilder = new CameraPosition.Builder();
positionBuilder.target(pos);
positionBuilder.zoom(15f);
positionBuilder.bearing(angle);
positionBuilder.tilt(60);
map.animateCamera(CameraUpdateFactory.newCameraPosition(positionBuilder.build()));
}
This overridden method was implementing on GoogleMap classes and map variable is variable that we define to load google map instance.
Please refer: https://developers.google.com/maps/documentation/android-sdk/views
I have used the following code to get the current location and path the route in google map. The problem i faced is that the current device location is not stable all the time. It shows correct location sometime but shows different location like 1km away from actual location.
package com.colors.organisatiom.activity.colors;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.colors.organisatiom.activity.colors.classes.ConnectionManager;
import com.colors.organisatiom.activity.colors.interfaces.PolyLineCallback;
import com.colors.organisatiom.activity.colors.json.GetDistanceFromServer;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import java.util.ArrayList;
import java.util.List;
public class LocationMap extends AppCompatActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap map;
private String serviceCentreLongitude, serviceCentreLatitude, serviceCenhterLocation;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
private RelativeLayout connectingParent;
private PolylineOptions polylineOptions;
private Polyline polyline;
private List<Polyline> polylines = new ArrayList<>();
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private static final long INTERVAL = 1 * 5;
private static final long FASTEST_INTERVAL = 10;
protected BroadcastReceiver mNotificationReceiver;
private Marker currentLocationMarker;
protected void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
serviceCentreLatitude = getIntent().getStringExtra("latitude");
serviceCentreLongitude = getIntent().getStringExtra("longitude");
serviceCenhterLocation = getIntent().getStringExtra("service_center_location");
setContentView(R.layout.content_google_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Window window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
}
mNotificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!LocationMap.this.isFinishing()) {
AlertDialog.Builder builder = new AlertDialog.Builder(LocationMap.this);
builder.setTitle(intent.getStringExtra("title"));
builder.setMessage(intent.getStringExtra("message"));
builder.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//alertDialog.dismiss();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
};
if (!isGooglePlayServicesAvailable()) {
Toast.makeText(this, "Google play service not supported", Toast.LENGTH_LONG).show();
}
createLocationRequest();
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
connectingParent = (RelativeLayout) findViewById(R.id.connecting_parent);
if (!new ConnectionManager(this).isConnectionToInternet()) {
connectingParent.setVisibility(View.GONE);
Toast.makeText(LocationMap.this, "No internet connection to route path", Toast.LENGTH_LONG).show();
}
ImageView search = (ImageView) findViewById(R.id.search);
search.setVisibility(View.INVISIBLE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasAccessCoarseLocationPermission = checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION);
int hasAccessFineLocationPermission = checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (hasAccessCoarseLocationPermission != PackageManager.PERMISSION_GRANTED && hasAccessFineLocationPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_ASK_PERMISSIONS);
} else {
showMapWithLocation();
if (googleApiClient.isConnected()) {
startLocationUpdates();
}
}
} else {
showMapWithLocation();
if (googleApiClient.isConnected()) {
startLocationUpdates();
}
}
}
#Override
public void onStart() {
super.onStart();
Log.d("Started:", "onStart fired ..............");
googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d("Stopped", "onStop fired ..............");
googleApiClient.disconnect();
Log.d("Is connected status", "isConnected ...............: " + googleApiClient.isConnected());
}
private void showMapWithLocation() {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng latLng = new LatLng(Double.parseDouble(serviceCentreLatitude), Double.parseDouble(serviceCentreLongitude));
map.addMarker(new MarkerOptions()
.position(latLng)
.title(serviceCenhterLocation)).showInfoWindow();
map.getUiSettings().setMapToolbarEnabled(false);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 14);
map.animateCamera(cameraUpdate);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startLocationUpdates();
if (googleApiClient.isConnected()) {
startLocationUpdates();
}
} else {
Toast.makeText(LocationMap.this, "Cannot show map", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
#Override
public void onConnected(Bundle bundle) {
Log.e("Connection status:", "onConnected - isConnected ...............: " + googleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
Log.e("Update started:", "Location update started ..............: ");
}
#Override
public void onLocationChanged(Location location) {
final double myLocationlatitude = location.getLatitude();
final double myLocationlongitude = location.getLongitude();
Log.e("Latitude", String.valueOf(myLocationlatitude));
Log.e("Longitude", String.valueOf(myLocationlongitude));
LatLng latLng = new LatLng(myLocationlatitude, myLocationlongitude);
//drawing the path in google map
//zoom the camera for the first time
if (currentLocationMarker != null) {
currentLocationMarker.remove();
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("My current location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
currentLocationMarker = map.addMarker(markerOptions);
if (polylines == null) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 14);
map.animateCamera(cameraUpdate);
}
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
new GetDistanceFromServer(String.valueOf(myLocationlatitude), String.valueOf(myLocationlongitude), serviceCentreLatitude, serviceCentreLongitude).drawPath(new PolyLineCallback() {
#Override
public void polyLinePointsHolder(String points) {
//remove the path and draw the path in google map while updating
if (polylines != null) {
for (Polyline line : polylines) {
line.remove();
}
}
List<LatLng> list = decodePoly(points);
polylineOptions = new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))
.geodesic(true);
polyline = map.addPolyline(polylineOptions);
polylines.add(polyline);
}
});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
connectingParent.setVisibility(View.GONE);
super.onPostExecute(aVoid);
}
}.execute();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("Connection Failed", connectionResult.getErrorMessage());
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
Log.d("TAG", "Location update stopped .......................");
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mNotificationReceiver, new IntentFilter("1000"));
if (googleApiClient.isConnected()) {
startLocationUpdates();
Log.d("TAG", "Location update resumed .....................");
}
}
}
The accuracy of location can be affected due to many factors including GPS coverage, device quality and wifi availability around the area. What you can do is to check the accuracy of the location you obtained and decide whether to proceed or not. For this you can use hasAccuracy() and getAccuracy() methods of the Location object.
Here is a quote from the documentation about getAccuracy method
Get the estimated accuracy of this location, in meters.
We define accuracy as the radius of 68% confidence. In other words, if
you draw a circle centered at this location's latitude and longitude,
and with a radius equal to the accuracy, then there is a 68%
probability that the true location is inside the circle.
In statistical terms, it is assumed that location errors are random
with a normal distribution, so the 68% confidence circle represents
one standard deviation. Note that in practice, location errors do not
always follow such a simple distribution.
This accuracy estimation is only concerned with horizontal accuracy,
and does not indicate the accuracy of bearing, velocity or altitude if
those are included in this Location.
If this location does not have an accuracy, then 0.0 is returned. All
locations generated by the LocationManager include an accuracy.
In your onLocationChanged method, you can do the following
#Override
public void onLocationChanged(Location location) {
if(location.hasAccuracy() && location.getAccuracy() < 100F) {
// the location has accuracy and has an accuracy span within 100m radius
// do whatever you want with this location and stop location listener
stopLocationUpdates();
}
// if the above code did not get executed, the location listener will work
// until a location with acceptable accuracy is obtained
}