How Get Location By Coarse Location
I'm trying to develo an app that get location by COARSE location. This app must run on Android 6 too than i've implemented permission request on run time, start the map but i can't
Solution 1:
Try this code with google fused location api
1) MainActivity.class
publicclassMainActivityextendsAppCompatActivityimplementsGoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
privateGoogleMap mMap;
publicstatic final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
publicstatic final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
protected final staticStringLOCATION_KEY = "location-key";
protected final staticStringLAST_UPDATED_TIME_STRING_KEY = "last-updated-time-string-key";
protectedGoogleApiClient mGoogleApiClient;
protectedLocationRequest mLocationRequest;
protectedLocation mCurrentLocation;
protectedString mLastUpdateTime;
privateboolean mycheck, chrckonce;
privateLocationManager manager;
privateDouble lat, lng;
privateContext context;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
chrckonce = true;
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLastUpdateTime = "";
updateValuesFromBundle(savedInstanceState);
}
@OverrideprotectedvoidonStart() {
super.onStart();
if (!manager.isProviderEnabled((LocationManager.GPS_PROVIDER))) {
//GPS is not available show alertAlertDialog.Builder alertDialog = newAlertDialog.Builder(context);
alertDialog.setTitle("GPS SETTINGS");
alertDialog.setMessage("GPS is not enable! Want to go to settings menu?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(" Settings", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stubIntent intent = newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
});
alertDialog.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
finish();
}
});
alertDialog.show();
} else {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mycheck = true;
buildGoogleApiClient();
mGoogleApiClient.connect();
mMap.setMyLocationEnabled(true);
}
}
@OverridepublicvoidonLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(newDate());
lat = location.getLatitude();
lng = location.getLongitude();
if (chrckonce) {
mMap.animateCamera(CameraUpdateFactory.newLatLng(newLatLng(lat, lng)), 2000, null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newLatLng(lat, lng), 18));
mMap.addMarker(newMarkerOptions().position(newLatLng(lat, lng)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
chrckonce = false;
}
}
//Update location from google fused apiprivatevoidupdateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
}
if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
}
}
}
//synchronized google fused location apiprotected synchronized voidbuildGoogleApiClient() {
mGoogleApiClient = newGoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
//create location requestprotectedvoidcreateLocationRequest() {
mLocationRequest = newLocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
//on resume activity@OverridepublicvoidonResume() {
super.onResume();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
}
//when activity goes on pause@OverrideprotectedvoidonPause() {
super.onPause();
if (mycheck == true) {
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
}
//when activity stops@OverrideprotectedvoidonStop() {
if (mycheck == true) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
@OverridepublicvoidonConnected(Bundle bundle) {
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(newDate());
}
startLocationUpdates();
}
//check connection suspended@OverridepublicvoidonConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
//Location updateprotectedvoidstartLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
//location update close when activity closedprotectedvoidstopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
@OverridepublicvoidonConnectionFailed(ConnectionResult connectionResult) {
}
}
2) activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:fitsSystemWindows="true"android:orientation="vertical"><fragmentandroid:id="@+id/map"android:name="com.google.android.gms.maps.MapFragment"android:layout_width="match_parent"android:layout_height="match_parent"></fragment></LinearLayout>
In Manifest permissions
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" /><uses-permissionandroid:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /><uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>
Post a Comment for "How Get Location By Coarse Location"