Geofence Notification - android

I am working on google geofence. I want to implement feature like UBER - when I enter or exit 100 meter radius, notification will come. I am getting the latitude and longitude from google places api which will be my geofence. Here is my MapActivity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
String Longitude, Latitude;
Location ll;
final String TAG = "GPS";
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
GoogleApiClient gac;
LocationRequest locationRequest;
int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
PlaceAutocompleteFragment autocompleteFragment;
Marker markerDesti, markerCurrentLoc;
LatLng DestiLoc;
double LatDesti, latCurrent;
double LonDesti, lngCurrent;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
PendingIntent mGeofencePendingIntent;
ArrayList<Geofence> mGeofenceList;
private GeofencingClient mGeofencingClient;
TextView TestBtn;
LocationRequest mLocationRequest;
private GeofancingResultCallBack geofancingResultCallBack;
public static final class Constants {
public static int GEOFENCE_RADIUS_IN_METERS = 1000;
public static int GEOFENCE_EXPIRATION_IN_MILLISECONDS = 1000;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
TestBtn = (TextView) findViewById(R.id.TestBtn);
isGooglePlayServicesAvailable();
if (!isLocationEnabled())
showAlert();
locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
gac = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//========================= PLACES API DROP DOWN============================//
mGeofencingClient = LocationServices.getGeofencingClient(this);
mGeofenceList = new ArrayList<>();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
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;
}
mMap.setMyLocationEnabled(true);
getPlacesApi();
}
#Override
protected void onStart() {
gac.connect();
super.onStart();
}
#Override
protected void onStop() {
gac.disconnect();
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
updateUI(location);
}
}
#Override
public void onConnected(#Nullable 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) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
Log.d(TAG, "onConnected");
ll = LocationServices.FusedLocationApi.getLastLocation(gac);
Log.d(TAG, "LastLocation: " + (ll == null ? "NO LastLocation" : ll.toString()));
Log.e("MYLatLonLocationService", ll.toString());
Latitude = Double.toString(ll.getLatitude());
Longitude = Double.toString(ll.getLongitude());
Toast.makeText(getApplicationContext(), Latitude + "\n" + Longitude, Toast.LENGTH_LONG).show();
Log.e("Lat&Lon", Latitude + "\n" + Longitude);
latCurrent = ll.getLatitude();
lngCurrent = ll.getLongitude();
LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
markerCurrentLoc = mMap.addMarker(new MarkerOptions()
.position(locCurrent)
.title("My Location"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
}
//=========== DRAW CURRENT LOCATION==============//
private void drawAllMarker() {
LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
//mMap.addMarker(new MarkerOptions().position(locCurrent).title("My Location"));
markerCurrentLoc = mMap.addMarker(new MarkerOptions()
.position(locCurrent)
.title("My Location"));
/*mMap.moveCamera(CameraUpdateFactory.newLatLng(locCurrent));
CameraPosition cameraPosition = new CameraPosition.Builder().target(
locCurrent).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
}
//=========== onRequestPermissionsResult ==============//
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MapsActivity.this, "Permission was granted!", Toast.LENGTH_LONG).show();
try {
LocationServices.FusedLocationApi.requestLocationUpdates(
gac, locationRequest, this);
} catch (SecurityException e) {
Toast.makeText(MapsActivity.this, "SecurityException:\n" + e.toString(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MapsActivity.this, "Permission denied!", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(MapsActivity.this, "onConnectionFailed: \n" + connectionResult.toString(),
Toast.LENGTH_LONG).show();
Log.d("DDD", connectionResult.toString());
}
private void updateUI(Location loc) {
Log.d(TAG, "updateUI");
/*tvLatitude.setText(Double.toString(loc.getLatitude()));
tvLongitude.setText(Double.toString(loc.getLongitude()));
tvTime.setText(DateFormat.getTimeInstance().format(loc.getTime()));*/
TestBtn.setText(Double.toString(loc.getLatitude()));
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
return;
}
ll = LocationServices.FusedLocationApi.getLastLocation(gac);
Log.d(TAG, "LastLocation: " + (ll == null ? "NO LastLocation" : ll.toString()));
Log.e("MYLatLonLocationService", ll.toString());
Latitude = Double.toString(ll.getLatitude());
Longitude = Double.toString(ll.getLongitude());
Toast.makeText(getApplicationContext(), Latitude + "\n" + Longitude, Toast.LENGTH_LONG).show();
Log.e("Lat&Lon", Latitude + "\n" + Longitude);
if (markerCurrentLoc != null) {
markerCurrentLoc.remove();
latCurrent = ll.getLatitude();
lngCurrent = ll.getLongitude();
LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
markerCurrentLoc = mMap.addMarker(new MarkerOptions()
.position(locCurrent)
.title("My Location"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(
locCurrent).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
}else {
latCurrent = ll.getLatitude();
lngCurrent = ll.getLongitude();
LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
markerCurrentLoc = mMap.addMarker(new MarkerOptions()
.position(locCurrent)
.title("My Location"));
markerCurrentLoc = mMap.addMarker(new MarkerOptions()
.position(locCurrent)
.title("My Location"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(
locCurrent).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
}
}
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isGooglePlayServicesAvailable() {
final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.d(TAG, "This device is not supported.");
finish();
}
return false;
}
Log.d(TAG, "This device is supported.");
return true;
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
//=========================== PLACES API=======================//
public void getPlacesApi() {
autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
if (markerDesti != null) {
markerDesti.remove();
LatDesti = place.getLatLng().latitude;
LonDesti = place.getLatLng().longitude;
Log.e("LatLonDest", String.valueOf(LatDesti));
DestiLoc = new LatLng(LatDesti, LonDesti);
markerDesti = mMap.addMarker(new MarkerOptions()
.position(DestiLoc)
.title("My Destination"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(DestiLoc));
CameraPosition cameraPosition = new CameraPosition.Builder().target(
DestiLoc).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGeofenceList.add(new Geofence.Builder()
.setRequestId("120")
.setCircularRegion(
LatDesti,
LonDesti,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
//geofancingResultCallBack.regesterAllGeofance();
//geofancingResultCallBack.myUpdateGeoFance(LatDesti, LonDesti);
//geofancingResultCallBack.getGeofencingRequest();
//geofancingResultCallBack.getmPendingIntent();
} else {
LatDesti = place.getLatLng().latitude;
LonDesti = place.getLatLng().longitude;
Log.e("LatLonDest", String.valueOf(LatDesti));
DestiLoc = new LatLng(LatDesti, LonDesti);
markerDesti = mMap.addMarker(new MarkerOptions()
.position(DestiLoc)
.title("My Destination"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(DestiLoc));
CameraPosition cameraPosition = new CameraPosition.Builder().target(
DestiLoc).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGeofenceList.add(new Geofence.Builder()
.setRequestId("120")
.setCircularRegion(
LatDesti,
LonDesti,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
//geofancingResultCallBack.regesterAllGeofance();
//geofancingResultCallBack.myUpdateGeoFance(LatDesti, LonDesti);
//geofancingResultCallBack.getGeofencingRequest();
//geofancingResultCallBack.getmPendingIntent();
}
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
.addOnSuccessListener(MapsActivity.this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Geofences added
Log.e("Geofencing Location service Api Client", "successfully added");
}
})
.addOnFailureListener(MapsActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Failed to add geofences
Log.e("Geofencing Location service Api Client", "unsuccessful");
}
});
//============================================================================================//
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//autocompleteFragment.onActivityResult(requestCode, resultCode, data);
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
Log.i(TAG, "Place:" + place.toString());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
Log.i(TAG, status.getStatusMessage());
} else if (requestCode == RESULT_CANCELED) {
}
}
}
//============================== GEO FANCING=================================//
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, BroadcastReciver.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
}
and my broadcast receiver is
public class BroadcastReciver extends BroadcastReceiver {
//Placer Geofence intent action name
public static final String INTENT_ACTION_TRIGGER_FIRED = "com.placer.action.TRIGGER_FIRED";
public static final String TAG1 = GeofanceBroadCastReciver.class.getSimpleName();
private static final String TAG = "GeofenceTransitions";
public BroadcastReciver() {
}
#Override
public void onReceive(Context context, Intent intent) {
/*GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()){
Log.e(TAG,String.format("Error code :%d",geofencingEvent.getErrorCode()));
return;
}
int geofenceTransition = geofencingEvent.getGeofenceTransition();
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER){
Log.e("Geo Fance ENTER","Geo Fance ENTER");
Toast.makeText(context, "Geo Fance ENTER", Toast.LENGTH_SHORT).show();
}else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT){
Log.e("Geo Fance EXIT","Geo Fance EXIT");
Toast.makeText(context,"Geo Fance EXIT",Toast.LENGTH_SHORT).show();
}
else {
Log.e(TAG,String.format("Unknown Transition :%",geofenceTransition));
return;
}
sendNotification(context,geofenceTransition);*/
if (intent.getAction().equals(INTENT_ACTION_TRIGGER_FIRED)) {
Log.e("ReciverWorking","ReciverWorking");
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
Log.e(TAG, "Goefencing Error " + geofencingEvent.getErrorCode());
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
Log.i(TAG, "geofenceTransition = " + geofenceTransition + " Enter : " + Geofence.GEOFENCE_TRANSITION_ENTER + "Exit : " + Geofence.GEOFENCE_TRANSITION_EXIT);
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL){
showNotification("Congrats!!!", "You have reached your destination..",context);
Toast.makeText(context,"Enter the Location",Toast.LENGTH_SHORT).show();
}
else if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Log.i(TAG, "Showing Notification...");
showNotification("Exited", "Exited the Location",context);
Toast.makeText(context,"Exited the Location",Toast.LENGTH_SHORT).show();
} else {
// Log the error.
showNotification("Error", "Error",context);
Log.e(TAG, "Error ");
}
}else {
throw new UnsupportedOperationException("Not yet implemented");
}
}
private void sendNotification(Context context,int transationType){
Intent notificationIntent = new Intent(context,MapsActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MapsActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent notificationpendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
if (transationType == Geofence.GEOFENCE_TRANSITION_ENTER){
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Entered");
}else if (transationType == Geofence.GEOFENCE_TRANSITION_EXIT) {
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("Exit");
}
builder.setContentText("Touch to launch the app");
builder.setContentIntent(notificationpendingIntent);
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
public void showNotification(String text, String bigText,Context context) {
// 1. Create a NotificationManager
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// 2. Create a PendingIntent for AllGeofencesActivity
Intent intent = new Intent(context, MapsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 3. Create and send a notification
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Congrats!!!")
.setContentText("You Have reached the destination")
.setContentIntent(pendingNotificationIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.build();
notificationManager.notify(0, notification);
}
the Android Manifest is:
<?xml version="1.0" encoding="utf-8"?>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".main.MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".adapters.GeofenceTransitionsIntentService"
android:exported="true" />
<receiver
android:name="com.map.pallabedp.locationbasedtracking.main.BroadcastReciver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.placer.action.TRIGGER_FIRED" />
<action android:name="my.action.string" />
<action android:name="com.map.pallabedp.locationbasedtracking.main.BroadcastReciver"/>
</intent-filter>
</receiver>
</application>
The problem is i am not getting any notification. Please help..

Related

Asking for location permission only appears when app is interrupted

I am developing an android application that uses Google Maps.
The expected behavior is:
Enter the map activity
Ask user to use his location
Show nearby places
When I run the application using an emulator in Android Studio , the flow is the expected one (Pixel 2 Api 30), but when I run it on my phone, the permission is only asked for after I stop the application run.
Why is this happening?
Acitivity
public class NearbyPharmaciesActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSION_CODE = 1000;
private GoogleMap mMap;
private double latitude, longitude;
private Location lastLocation;
private Marker marker;
private GoogleMapsApi mService;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback locationCallback;
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_pharmacies);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Init service
mService = RetrofitGoogleMaps.getApi();
// Request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_pharmacy:
nearbyPlaces("pharmacy");
break;
default:
break;
}
return true;
}
});
buildLocationCallBack();
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
private boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
}, MY_PERMISSION_CODE);
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
}, MY_PERMISSION_CODE);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
buildLocationCallBack();
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
}
break;
}
}
private void buildLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(300000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setSmallestDisplacement(30);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void buildLocationCallBack() {
System.out.println("Reached here");
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
lastLocation = locationResult.getLastLocation();
System.out.println("last location: " + lastLocation.toString());
if (marker != null) {
marker.remove();
}
latitude = lastLocation.getLatitude();
longitude = lastLocation.getLongitude();
System.out.println("LATITUDE: " + latitude);
System.out.println("LONGITUDE: " + longitude);
LatLng latLng = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
marker = mMap.addMarker(options);
//LocationData locationData = new LocationData(latitude, longitude);*/
//mDatabase.child("location").child(userId).child(String.valueOf(new Date().getTime())).setValue(locationData);
//getMarkers();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
};
}
#Override
public void onMapReady(#NonNull 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 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
mMap.setMyLocationEnabled(true);
}
}
}
private void nearbyPlaces(final String placeType) {
String url = getUrl(latitude, longitude, placeType);
System.out.println("URL: "+ url);
mService.getNearByPlaces(url)
.enqueue(new Callback<SearchResponse>() {
#Override
public void onResponse(Call<SearchResponse> call, Response<SearchResponse> response) {
if (response.isSuccessful()) {
System.out.println("Sucesso");
for (int i = 0; i < response.body().getResults().length; i++) {
System.out.println("ENTRA NO IF");
MarkerOptions markerOptions = new MarkerOptions();
Result googlePlace = response.body().getResults()[i];
double lat = Double.parseDouble(googlePlace.getGeometry().getLocation().getLat());
double lng = Double.parseDouble(googlePlace.getGeometry().getLocation().getLng());
String placeName = googlePlace.getName();
String vicinity = googlePlace.getVicinity();
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName);
if (placeType.equals("pharmacy")) {
System.out.println("BEM");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
} else {
System.out.println("CONA");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
mMap.addMarker(markerOptions);
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
}
}
}
#Override
public void onFailure(Call<SearchResponse> call, Throwable t) {
}
});
}
private String getUrl(double latitude, double longitude, String placeType) {
StringBuilder builder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
builder.append("location=" + latitude + "," + longitude);
builder.append("&radius=10000");
builder.append("&type=" + placeType);
builder.append("&sensor=true");
builder.append("&key=" + "XXXXXXXXXXXXXXXXXXXXXXXX");
Log.d("getUrl", builder.toString());
return builder.toString();
}
}
Found the problem.
This happened because I asked for permissions in two separate occasions.
First I would ask for SMS permissions in my Main Activity and then, when entering this Activity I would ask for location permissions.
In android development you must ask for all permissions at once.

GEOFENCE_NOT_AVAILABLE error when I try to set a geofence area

Can someone explain me what am I doing wrong, when I press on the screen I want to set a geofence area, I can see on the screen that the are is created but I'm getting and error that "GEOFENCE_NOT_AVAILABLE".
ON my app setting the app has location permission;
Maps.java
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
private GoogleMap mMap;
private GeofencingClient geofencingClient;
private GeofenceHelper geofenceHelper;
private int FINE_LOCATION_ACCESS_REQUEST_CODE = 10001;
private float GEOFENCE_RADIUS = 200;
private String GEOFENCE_ID = "SOMEID";
#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);
geofencingClient = LocationServices.getGeofencingClient(this);
geofenceHelper = new GeofenceHelper(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng office = new LatLng(33.822, -116.5379);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(office, 16));
enableUserLocation();
mMap.setOnMapLongClickListener(this);
}
private void enableUserLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_ACCESS_REQUEST_CODE);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION_ACCESS_REQUEST_CODE);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == FINE_LOCATION_ACCESS_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
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);
} else {
}
}
}
#Override
public void onMapLongClick(#NonNull LatLng latLng) {
mMap.clear();
addMarker(latLng);
addCircle(latLng, GEOFENCE_RADIUS);
addGeofence(latLng, GEOFENCE_RADIUS);
}
private void addGeofence(LatLng latLng, float radius) {
Geofence geofence = geofenceHelper.getGeofence(GEOFENCE_ID, latLng, radius, Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_DWELL | Geofence.GEOFENCE_TRANSITION_EXIT);
GeofencingRequest geofencingRequest = geofenceHelper.geofencingRequest(geofence);
PendingIntent pendingIntent = geofenceHelper.getPendingIntent();
geofencingClient.addGeofences(geofencingRequest, pendingIntent).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.e("TAG", "Geocende added");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String errorMessage = geofenceHelper.getErrorString(e);
Log.e("TAG", "onFailure: " + errorMessage);
}
});
}
private void addMarker(LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions().position(latLng);
mMap.addMarker(markerOptions);
}
private void addCircle(LatLng latLng, float radius) {
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(latLng);
circleOptions.radius(radius);
circleOptions.strokeColor(Color.argb(255, 255, 0, 0));
circleOptions.fillColor(Color.argb(64, 255, 0, 0));
circleOptions.strokeColor(4);
mMap.addCircle(circleOptions);
}
}
GeofenceHelper.java
public class GeofenceHelper extends ContextWrapper {
private static final String TAG = "GeofenceHelper";
PendingIntent pendingIntent;
public GeofenceHelper(Context base) {
super(base);
}
public GeofencingRequest geofencingRequest (Geofence geofence) {
return new GeofencingRequest.Builder()
.addGeofence(geofence)
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.build();
}
public Geofence getGeofence(String ID, LatLng latLng, float radius, int transitionTypes) {
return new Geofence.Builder()
.setCircularRegion(latLng.latitude, latLng.longitude, radius)
.setRequestId(ID)
.setTransitionTypes(transitionTypes)
.setLoiteringDelay(5000)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
}
public PendingIntent getPendingIntent() {
if (pendingIntent != null) {
return pendingIntent;
}
Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 2607, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
public String getErrorString(Exception e) {
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
switch (apiException.getStatusCode()) {
case GeofenceStatusCodes
.GEOFENCE_NOT_AVAILABLE:
return "GEOFENCE_NOT_AVAILABLE";
case GeofenceStatusCodes
.GEOFENCE_TOO_MANY_GEOFENCES:
return "GEOFENCE_TOO_MANY_GEOFENCES";
case GeofenceStatusCodes
.GEOFENCE_TOO_MANY_PENDING_INTENTS:
return "GEOFENCE_TOO_MANY_PENDING_INTENTS";
}
}
return e.getLocalizedMessage();
}
}
GoefenceBroadcastReceiver.java
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Geofence trigerred...", Toast.LENGTH_SHORT).show();
}
}

Not getting geofence notification based on location radius

I am trying to implement geofencing in an app. As soon as user enters in the radius of geofence a notification is shown to the user and I have tried the below code but not getting notifications.Latitude and longitude are based on my location inside radius of geofencing.Any help will be appreciated :
MainActivity.java
public class MainActivity extends AppCompatActivity implements LocationListener{
PendingIntent mGeofencePendingIntent;
public static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 100;
private List<Geofence> mGeofenceList;
private GoogleApiClient mGoogleApiClient;
public static final String TAG = "Activity";
LocationRequest mLocationRequest;
double currentLatitude = 23.0023593, currentLongitude = 72.6665668;
Boolean locationFound;
protected LocationManager locationManager;
protected LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
mGeofenceList = new ArrayList<Geofence>();
int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resp == ConnectionResult.SUCCESS) {
initGoogleAPIClient();
createGeofences(currentLatitude, currentLongitude);
} else {
Log.e(TAG, "Your Device doesn't support Google Play Services.");
}
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1000)
.setFastestInterval(1000);
}
}
public void initGoogleAPIClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(connectionAddListener)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
mGoogleApiClient.connect();
}
private GoogleApiClient.ConnectionCallbacks connectionAddListener =
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "onConnected");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.i(TAG, currentLatitude + " WORKS " + currentLongitude);
createGeofences(currentLatitude, currentLongitude);
}
try {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Saving Geofence");
} else {
Log.e(TAG, "Registering geofence failed: " + status.getStatusMessage() +
" : " + status.getStatusCode());
}
}
});
} catch (SecurityException securityException) {
Log.e(TAG, "Error");
}
}
#Override
public void onConnectionSuspended(int i) {
Log.e(TAG, "onConnectionSuspended");
}
};
public void createGeofences(double latitude, double longitude) {
String id = UUID.randomUUID().toString();
Geofence fence = new Geofence.Builder()
.setRequestId(id)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(latitude, longitude, 1000)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeofenceList.add(fence);
}
private GoogleApiClient.OnConnectionFailedListener connectionFailedListener =
new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed");
}
};
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
private PendingIntent getGeofencePendingIntent() {
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
#Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.i(TAG, "onLocationChanged");
}
}
GeofenceTransitionsIntentService.java
public class GeofenceTransitionsIntentService extends IntentService {
private static final String TAG = "GeofenceTransitions";
public GeofenceTransitionsIntentService() {
super("GeofenceTransitionsIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "onHandleIntent");
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
//String errorMessage = GeofenceErrorMessages.getErrorString(this,
// geofencingEvent.getErrorCode());
Log.e(TAG, "Goefencing Error " + geofencingEvent.getErrorCode());
return;
}
int geofenceTransition = geofencingEvent.getGeofenceTransition();
Log.i(TAG, "geofenceTransition = " + geofenceTransition + " Enter : " + Geofence.GEOFENCE_TRANSITION_ENTER + "Exit : " + Geofence.GEOFENCE_TRANSITION_EXIT);
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL){
showNotification("Entered", "Entered the Location");
}
else if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Log.i(TAG, "Showing Notification...");
showNotification("Exited", "Exited the Location");
} else {
showNotification("Error", "Error");
Log.e(TAG, "Error ");
}
}
public void showNotification(String text, String bigText) {
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentText(text)
.setContentIntent(pendingNotificationIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.build();
notificationManager.notify(0, notification);
}
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.geofincingdemo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".GeofenceTransitionsIntentService"
android:exported="true" />
</application>
</manifest>
My GPS is also on with high accuracy and I am running on API Level 23.

without turn on location not showing current location in android

Hi in the below code am setting current location to my application.If it is turn on the location by manually it was showing current location.
If am not turn it on it was showing nothing in my map.
But i want to display the permission to turn on location and have written the code but it is not working .
can any one please help to resolve this issue.
MapsActivity.java:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int LOCATION_REQUESTOR = 101;
#Bind(R.id.back)
TextView mBack;
#Bind(R.id.location)
TextView mLocation;
#Bind(R.id.toolBar)
Toolbar mToolBar;
#Bind(R.id.map_address)
TextView mMapAddress;
#Bind(R.id.latitude)
EditText mLatitude;
#Bind(R.id.longitude)
EditText mLongitude;
#Bind(R.id.setLocation)
Button mSetLocation;
private Location mLastLocation;
private GoogleMap mMap;
Marker mCurrLocationMarker;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private SharedPreferences mPref;
private SolarBLEPacket mSolarController = new SolarBLEPacket();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ButterKnife.bind(this);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
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(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);
}
}
#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();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
mLongitude.setText(latLng.longitude + "");
mLatitude.setText(latLng.latitude + "");
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap=googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//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) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean 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(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.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);
}
return false;
} else {
return true;
}
}
#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) {
//Request location updates:
//.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
#OnClick(R.id.setLocation)
public void onClick() {
Intent intent = new Intent();
String longtitude = mLongitude.getText().toString();
if (!TextUtils.isEmpty(longtitude)) {
intent.putExtra(Constants.LONGITUDE, longtitude);
} else {
Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
return;
}
String latitude = mLatitude.getText().toString();
if (!TextUtils.isEmpty(latitude)) {
intent.putExtra(Constants.LATITUDE, latitude);
} else {
Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
return;
}
String latCommand = mSolarController.generatePacket("lat " +latitude,"00");
String longitudeCmd = mSolarController.generatePacket("lon "+longtitude,"00");
mPref.edit().putString(Constants.LAT_COMMAND,latCommand).commit();
mPref.edit().putString(Constants.LONG_COMMAND,longitudeCmd).commit();
mPref.edit().putString(Constants.LAST_LATITUDE,latitude).commit();
mPref.edit().putString(Constants.LAST_LONGITUDE,latitude).commit();
setResult(RESULT_OK, intent);
finish();
}
#OnClick({R.id.back, R.id.location})
public void onClick(View view) {
switch (view.getId()) {
case R.id.back:
setResult(RESULT_OK, new Intent());
finish();
break;
case R.id.location:
Intent intent = new Intent();
String longtitude = mLongitude.getText().toString();
if (!TextUtils.isEmpty(longtitude)) {
intent.putExtra(Constants.LONGITUDE, longtitude);
} else {
Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
return;
}
String latitude = mLatitude.getText().toString();
if (!TextUtils.isEmpty(latitude)) {
intent.putExtra(Constants.LATITUDE, latitude);
} else {
Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
return;
}
Float lat = Float.parseFloat(latitude);
if (lat > 90 || lat < -90) {
Toast.makeText(this, R.string.longitude_alert, Toast.LENGTH_SHORT).show();
return;
}
float lan = Float.parseFloat(longtitude);
if (lan > 180 || lan < -180) {
Toast.makeText(this, R.string.latitude_alert, Toast.LENGTH_SHORT).show();
return;
}
String latCommand = mSolarController.generatePacket("lat "+latitude,"00");
String longitudeCmd = mSolarController.generatePacket("long "+longtitude,"00");
mPref.edit().putString(Constants.LAT_COMMAND,latCommand).commit();
mPref.edit().putString(Constants.LONG_COMMAND,longitudeCmd).commit();
mPref.edit().putString(Constants.LAST_LATITUDE,latitude).commit();
mPref.edit().putString(Constants.LAST_LONGITUDE,latitude).commit();
setResult(RESULT_OK, intent);
finish();
break;
}
}
}
You are just checking the permission, You need to check whether is location is enable of the device or not.
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}

How I display my current location in google map? [duplicate]

This question already has answers here:
How can I show current location on a Google Map on Android Marshmallow?
(3 answers)
Closed 4 years ago.
I wants to display my location in android device in google may using marker. I have written the following code. But there has no marker in the map. I also implement the LocationListener. But no marker. I am thankful to you if you send some code or give some suggestion.
I am also checking the isProviderAvailable and provider. They are not coming properly. isProviderAvailable returns false. Is I have to change some facility on my device? or any other problem. Please share your thought. I am waiting.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private LocationManager mLocationManager = null;
private String provider = null;
private Marker mCurrentPosition = null;
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Toast.makeText(this, "locateCurrentPosition Test", Toast.LENGTH_SHORT).show();
if (isProviderAvailable() && (provider != null)) {
locateCurrentPosition();
}
else
{
Toast.makeText(this, "Not satisfied:"+isProviderAvailable(), Toast.LENGTH_SHORT).show();
}
}
private void locateCurrentPosition() {
Toast.makeText(this, "locateCurrentPosition", Toast.LENGTH_SHORT).show();
int status = getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist,
this);
}
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(10f).build();
if (mMap != null)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
private void addBoundaryToCurrentPosition(double lat, double lang) {
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker));
mMarkerOptions.anchor(0.5f, 0.5f);
CircleOptions mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(10000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
mMap.addCircle(mOptions);
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
}
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
}
Mainfest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "26.0.2"
defaultConfig {
applicationId "com.live.bbw.locationtest"
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.google.android.gms:play-services-maps:11.0.4'
testCompile 'junit:junit:4.12'
}
if you need to fetch current location lat and log value and also show marker.
fetch current location lat and long value and show marker on that used below code ...
public class MapLocationActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public 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)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//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) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.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(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);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(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());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(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(MapLocationActivity.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
}
}
}
if you want only fetch current location lat and long value and some interval time used below class i make for separate ...
public class LocationFetcher implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
// LogCat tag
private static final String TAG = LocationFetcher.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mBestReading;
private static final long ONE_MIN = 1000 * 60;
private static final long TWO_MIN = ONE_MIN * 2;
private static final long FIVE_MIN = ONE_MIN * 5;
private static final long POLLING_FREQ = 1000 * 30;
private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
private static final float MIN_ACCURACY = 25.0f;
private static final float MIN_LAST_READ_ACCURACY = 500.0f;
private double mLattitude;
private double mLongitue;
private double mAltitude;
private Activity mContext;
private UpdatedLocation updatedLocation;
private Location mLocation;
public void setListener(UpdatedLocation updatedLocation) {
if(mGoogleApiClient == null) {
init();
}
this.updatedLocation = updatedLocation;
updateLocation();
}
public void removeListener(){
this.updatedLocation = null;
mGoogleApiClient = null;
/*if(mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}*/
}
public LocationFetcher(Activity context) {
// First we need to check availability of play services
this.mContext = context;
// init();
// Show location button click listener
}
private void init(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(POLLING_FREQ);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
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 {
status.startResolutionForResult(mContext, 101);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
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;
}
}
});
}
private boolean servicesAvailable() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
//TODO ALERT
Toast.makeText(mContext,
"context device is not supported.", Toast.LENGTH_LONG)
.show();
return false;
}
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
if (servicesAvailable()) {
// Get best last location measurement meeting criteria
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
if (null == mBestReading
|| mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
|| mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(location != null) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
}
return;
}
}
}
}
private Location bestLastKnownLocation(float minAccuracy, long minTime) {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
long bestTime = Long.MIN_VALUE;
// Get the best most recent location currently available
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (mCurrentLocation != null) {
float accuracy = mCurrentLocation.getAccuracy();
long time = mCurrentLocation.getTime();
if (accuracy < bestAccuracy) {
bestResult = mCurrentLocation;
bestAccuracy = accuracy;
bestTime = time;
}
}
if (bestAccuracy > minAccuracy || bestTime < minTime) {
return null;
} else {
mLocation = bestResult;
mLattitude = bestResult.getLatitude();
mLongitue = bestResult.getLongitude();
mAltitude = bestResult.getAltitude();
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
return bestResult;
}
}
return null;
}
return null;
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(android.location.Location location) {
mLocation = location;
mLattitude = location.getLatitude();
mLongitue = location.getLongitude();
// mLattitude = 23.0394070;
// mLongitue = 72.5638900;
if(updatedLocation != null)
updatedLocation.updateUI(location);
CustomLogHandler.printDebuglog("Location","========>>" + location);
}
public Location getLocation(){
return mLocation;
}
public double getLatitude(){
return mLattitude;
}
public double getLongitude(){
return mLongitue;
}
public double getAltitude(){
return mAltitude;
}
public void updateLocation(){
bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
}
public interface UpdatedLocation {
public void updateUI(Location location);
}
}
get latlng and put it in the code that i wrote bellow and put it on your OnMapReadyCallback
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if you have any other questions im there
You can retrieve onLocationChanged Listener and Add maker init
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
Implement your onLocationChanged like this
#Override
public void onLocationChanged(Location location) {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
Marker marker = mMap.addMarker(new MarkerOptions().position(latLng));
marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
} else {
Toast.makeText(getContext(), "Location not found", Toast.LENGTH_SHORT).show();
}
}

Categories

Resources