hey this is my code for retrieving users location periodically
#Override
protected void onCreate(Bundle savedInstanceState) {
buildGoogleApiClient();
}
private void prepareLocationServices() {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
}
private void buildGoogleApiClient() {
if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) {
googleApiClient.connect();
}
}
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.d("location", location.toString());
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
prepareLocationServices();
}
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
prepareLocationServices();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
buildGoogleApiClient();
}
but onLocationChanged is not calling at all while I have Cellular Data and GPS enabled. What is wrong?
Related
I have made a simple sample of the FusedLocationProviderClient according to this: https://developer.android.com/training/location/request-updates#java
The issue is that I get a location every now and then (waaaay above an interval of 4000ms) and the accuracy is 2000 meters. I need a more precise location and more often. I get the feeling that the location client is not set up properly but at the same time, when using the locationmanager I also get a slow update rate on gps when using the gps provider, network provider also gives me an accuracy of 2000 meters.
Here is my code:
public class MainActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {
Context context;
private LocationCallback locationCallback;
private FusedLocationProviderClient fusedLocationClient;
private LocationRequest locationRequest;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
locationRequest = new LocationRequest();
locationRequest.setFastestInterval(2000);
locationRequest.setInterval(4000);
locationRequest.setMaxWaitTime(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
fusedLocationClient = new FusedLocationProviderClient(this);
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.e("Got location from provider " + location.getProvider(), location.getLatitude() + ", " + location.getLongitude());
Log.e("getAccuracy", String.valueOf(location.getAccuracy()));
}
}
#Override
public void onLocationAvailability(#NonNull LocationAvailability locationAvailability) {
super.onLocationAvailability(locationAvailability);
Log.e("asdf", "available");
}
};
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = {android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(this, PERMISSIONS, 112);
return;
}
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
private void stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
#Override
public void onRequestPermissionsResult(int i, #NonNull String[] strings, #NonNull int[] ints) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
startLocationUpdates();
}
public void onPause() {
super.onPause();
stopLocationUpdates();
}
}
How can I resolve this?
Actually i created a application to show the nearest Fuel station, so i use the FusedLocationApi for that, and in the code first i check the use location is enabled or not, If no than i build GoogleClient and call setingsrequest() function and if location is ON than application works perfectly but when location OFF than aaplication is crash.. please check logs
logs :
E/UncaughtException: java.lang.IllegalStateException: GoogleApiClient
is not connected yet.
at com.google.android.gms.internal.zzbcc.zze(Unknown Source)
at com.google.android.gms.internal.zzbcw.zze(Unknown Source)
at com.google.android.gms.internal.zzbco.zze(Unknown Source)
at
com.google.android.gms.internal.zzcca.requestLocationUpdates(Unknown
Source)
at
activities.FuelStations.onConnected(FuelStations.java:356)
at com.google.android.gms.common.internal.zzac.zzn(Unknown Source)
at com.google.android.gms.internal.zzbco.zzm(Unknown Source)
at com.google.android.gms.internal.zzbcc.zzpY(Unknown Source)
at com.google.android.gms.internal.zzbcc.onConnected(Unknown Source)
at com.google.android.gms.internal.zzbcw.onConnected(Unknown Source)
at com.google.android.gms.internal.zzbbh.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzaa.onConnected(Unknown
Source)
at com.google.android.gms.common.internal.zzn.zzrj(Unknown Source)
at com.google.android.gms.common.internal.zze.zzs(Unknown Source)
at com.google.android.gms.common.internal.zzi.zzrk(Unknown Source)
at com.google.android.gms.common.internal.zzh.handleMessage(Unknown
Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Updated code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_fuel_stations);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
LocationManager mlocManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
final boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!enabled) {
mGoogleApiClient.connect();
setingsrequest();
}
else
{
init();
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
public void setingsrequest()
{
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(FuelStations.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Toast.makeText(getApplicationContext(),"Location is on",Toast.LENGTH_SHORT).show();
init();
break;
case Activity.RESULT_CANCELED:
//keep asking if imp or do whatever
finish();
break;
}
break;
}
}
private void init(){
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
tempGoogleMap = mGoogleMap;
//MAP_FLAG=1;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
} else {
checkLocationPermission();
}
} else {
mGoogleApiClient.connect();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMapToolbarEnabled(true);
//the below listener is depreceated so i have to find a different way
// mGoogleMap.setOnMyLocationButtonClickListener(myLocationChangeListener);
mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
Location loc = mGoogleMap.getMyLocation();
LatLng currentLoc = new LatLng(loc.getLatitude(), loc.getLongitude());
mGoogleMap.clear();
markerOptions.position(currentLoc);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLoc,15.0f));
nearestFuelStation();
return true;
}
});
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
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(FuelStations.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();
}
mGoogleMap.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
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent= new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
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;
} startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
} else {
// Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionSuspended(int i) {
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(this, "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(getApplicationContext(),"Connection Failed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
if (mGoogleMap!=null)
mGoogleMap.clear();
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15.0f));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
nearestFuelStation();
}
private void nearestFuelStation() {
String FuelStation = "gas_station";
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
}
#Override
protected void onStart() {
if(mGoogleApiClient != null){
mGoogleApiClient.connect();
}
super.onStart();
Log.d("client value", String.valueOf(mGoogleApiClient.isConnected()));
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStop() {
// Disconnecting the client invalidates it.
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
if(mGoogleApiClient!=null){
{
mGoogleApiClient.disconnect();}
}
super.onStop();
}
// Trigger new location updates at interval
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
}
you are trying to access location before mGoogleApiClient is connected,call setingsrequest() method from onConnected method that executed on mGoogleApiClient is connected
replace
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
with
#Override
public void onConnected(Bundle bundle) {
LocationManager mlocManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
final boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
setingsrequest();
} else {
init();
}
}
I have following script to get Location using GoogleAPI. Working on My App is based on Location. When This Activity was opened, thanks to using GoogleAPI is got Location Known as Latitude and Longitude.
When MainActivity is opened, if Location turns on within Device Settings.(Android smart Phone).Location Knowledge is obtained as a successfully way and in MainActivity doesn't happen any Problems. Conversely, when Location Turns off on
my android device, while the Activity is started, I have error and App close with a message that called "Unfortunately The App has stopped".
How can I solve this problem? while The Activity is opening How to Control whether Location turns on or off.
thanks in advance for the whole help.
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
, LocationListener , DialogInterface.OnClickListener {
public static final String KEY_LOC_ADD_URL = "http://xxxxxxxx/android_api/insertlocation.php";
public static final String KEY_LATITUDE = "enlem";
public static final String KEY_LONGITUDE = "boylam";
public static final String KEY_ID="id";
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location mevcutKonum;
private String[] seconds={"1","3","5","7","10"};
private String sonGuncellemeZamani;
private String employee_id;
private Long requestTime;
private TextView enlemTextView;
private TextView boylamTextView;
private TextView sonGuncellemeTextView;
private TextView employee_name;
private AlertDialog dialogSelectInternal;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enlemTextView = (TextView) findViewById(R.id.enlem);
boylamTextView = (TextView) findViewById(R.id.boylam);
sonGuncellemeTextView = (TextView) findViewById(R.id.guncellemezamani);
sonGuncellemeZamani = "";
employee_name= (TextView) findViewById(R.id.userName);
Intent intent = getIntent();
employee_name.setText("Welcome User " + intent.getStringExtra(Login_Activity.KEY_USERNAME));
employee_id=intent.getStringExtra(Login_Activity.KEY_ID);
buildGoogleApiClient();
selectRequestTimeDialog();
createLocationRequest();
}
protected void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
locationRequest = LocationRequest.create()
.setInterval(3000)
.setFastestInterval(1000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void updateUI() {
if (mevcutKonum != null) {
enlemTextView.setText(String.valueOf(mevcutKonum.getLatitude()));
boylamTextView.setText(String.valueOf(mevcutKonum.getLongitude()));
sonGuncellemeTextView.setText(sonGuncellemeZamani);
}
}
#Override
protected void onResume() {
super.onResume();
googleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (googleApiClient.isConnected()) {
stopLocationUpdates();
}
googleApiClient.disconnect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mevcutKonum == null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mevcutKonum = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
try {
addLocationToUser(String.valueOf(mevcutKonum.getLatitude()),String.valueOf(mevcutKonum.getLongitude()),employee_id);
} catch (JSONException e) {
e.printStackTrace();
}
updateUI();
}
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mevcutKonum = location;
sonGuncellemeZamani = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void addLocationToUser(final String latitude, final String longitude,final String id) throws JSONException {
StringRequest stringRequest = new StringRequest(Request.Method.POST, KEY_LOC_ADD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put(KEY_LATITUDE,latitude);
params.put(KEY_LONGITUDE, longitude);
params.put(KEY_ID,id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void selectRequestTimeDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Konumunuzu Güncellemek istediğiniz zaman aralığını seçiniz");
builder.setItems(seconds,this);
builder.setNegativeButton("Cancel", null);
dialogSelectInternal=builder.create();
dialogSelectInternal.show();
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
Above Code has worked when location only turns on
In your onCreate() , First check if your GPS is enabled in your device, if yes create location update, else go to Location Settings.
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createLocationRequest();
} else {
Toast.makeText(this, "Please enable your gps first.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent, 1);
}
On GPS -> HIGH ACCURACY selection:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
switch (requestCode) {
case 1:
createLocationRequest();
break;
}
}
}
Hope this helps.
My google maps app is sending my coordinates every 5 seconds after I click the button (mapbttn). I want to make another button to stop sending these coordinates. How can I do that?
Here is my .java file:
private GoogleMap mMap;
Button mapbttn;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapbttn = (Button) findViewById(R.id.setRangeButton);
mapbttn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btncoord();
}
});
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(), "" + location.getLatitude() + '\n' + location.getLongitude(), Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
public void onProviderDisabled(String s) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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);
return;
} else {
btncoord();
}
}
Bundle save = getIntent().getExtras();
if (save != null) color = save.getString("marker color");
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
btncoord();
return;
}
}
public void btncoord() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 5000, 0, locationListener);
}
Simply un-register your location manager like
locationManager.removeUpdates(ActivityName.this);
docs
Try this
public void stopUpdates(){
locationManager.removeUpdates(context);
}
call stopUpdate() method on stop button.
I am creating an app, i want to turn on location settings when press on allow button. when my app starts first it works properly going to the current location but when i close the app and start again it not get on to the current location. So please help me using my source code.....
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// 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);
createLocationRequest();
}
private void createLocationRequest() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates states =
result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// initialize location requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MapsActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way
// to fix the settings so we won't show the dialog.
break;
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
//settingsrequest();//keep asking if imp or do whatever
break;
}
break;
}
}
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}else{
return true;
}
}
#Override
public void onConnected(Bundle bundle) {
/*mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
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);
}*/
if(checkLocationPermission()){
startLocationUpdates();
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(mCurrLocationMarker != null){
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOption);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
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 onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION: {
if(grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
Please help me...
Thanks
Implement this :
#Override
protected void onResume() {
super.onResume();
if (mLocationRequest != null && mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
Also i can't see onStart() and onStop() . Maybe this is helpful
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
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);
//createLocationRequest();
}
}
My error is come on "LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);"
when i start app on second time..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
createLocationRequest();
}