**MapsActivity:**
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationObserver {
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 200;
ArrayList<LatLng> paths;
Marker mPositionMarker = null;
int height;
int width;
String startName = null, endName = null;
private GoogleMap mMap;
private ArrayList<LatLng> markerPoints = new ArrayList<>();
private TextView distanceValue;
private SupportMapFragment mapFragment;
private boolean isPermissionGranted;
private LatLng myLatLng;
private LocationData locationData;
private static String downloadUrl(String strUrl) throws IOException {
String data = "";
HttpURLConnection urlConnection;
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
try (InputStream iStream = urlConnection.getInputStream()) {
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
//String line = "";
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
urlConnection.disconnect();
}
return data;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
locationData = new LocationData(this);
locationData.registerObserver(this);
checkForPermission();
paths = new ArrayList<>();
}
public void updateUI() {
mapFragment.getMapAsync(this);
distanceValue = findViewById(R.id.tv_distance_value);
}
@Override
public void update(Double lat, Double lng) {
myLatLng = new LatLng(lat, lng);
if (!isPermissionGranted) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, 16));
updateUI();
isPermissionGranted = true;
}
Location location = new Location("");
location.setLatitude(lat);
location.setLongitude(lng);
animateMarker(mPositionMarker, location); // Helper method for smooth
}
public void animateMarker(final Marker marker, final Location location) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final LatLng startLatLng = marker.getPosition();
final double startRotation = marker.getRotation();
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * location.getLongitude() + (1 - t)
* startLatLng.longitude;
double lat = t * location.getLatitude() + (1 - t)
* startLatLng.latitude;
float rotation = (float) (t * location.getBearing() + (1 - t)
* startRotation);
marker.setPosition(new LatLng(lat, lng));
marker.setRotation(rotation);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
public void checkForPermission() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(this, "Application need Access fine Location permission", Toast.LENGTH_SHORT).show();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(this, "Application need Access coarse Location permission", Toast.LENGTH_SHORT).show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
} else {
updateUI();
}
}
@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) {
return;
}
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
distanceValue.setText("");
if (myLatLng != null) {
if (markerPoints.size() == 0) {
markerPoints = paths;
//markerPoints.add(0, myLatLng);
} else {
markerPoints = paths;
markerPoints.set(0, myLatLng);
}
}
if (markerPoints.size() > 0) {
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
MarkerOptions optionstart = new MarkerOptions();
MarkerOptions optionsend = new MarkerOptions();
// Setting the position of the marker
int pathsize = paths.size();
for (int i = 0; i < pathsize; i++) {
LatLng latLng = (paths.get(i));
options.position(latLng);
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
}
optionstart.title(startName);
optionsend.title(endName);
int lastPoint = markerPoints.size() - 1;
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(lastPoint);
String url = getDirectionsUrl(origin, dest);
ParserTask parserTask = new ParserTask(this);
parserTask.execute(valueOf(url));
LatLngBounds.Builder binder = new LatLngBounds.Builder();
for (LatLng latLngPoint : markerPoints) {
binder.include(latLngPoint);
}
LatLngBounds bounds = binder.build();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
}
}
@Override
protected void onResume() {
super.onResume();
locationData.registerObserver(this);
}
@Override
protected void onPause() {
super.onPause();
locationData.unregisterObserver(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
@NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isPermissionGranted = true;
updateUI();
} else {
isPermissionGranted = false;
Toast.makeText(this, "Please allow all permissions", Toast.LENGTH_SHORT).show();
}
}
}
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
String mode = "mode=driving";
StringBuilder wayPoints = new StringBuilder();
for (int i = 1; i < markerPoints.size() - 1; i++) {
LatLng point = markerPoints.get(i);
if (i == 1)
wayPoints = new StringBuilder("waypoints=");
wayPoints.append(point.latitude).append(",").append(point.longitude).append("|");
}
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode + "&" + wayPoints;
// Output format
String output = "json";
return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
}
public MapsActivity(){}
private static class ParserTask extends AsyncTask<String, Integer, ArrayList<LatLng>> {
ArrayList<Object> points = null;
DirectionsJSONParser parser;
private WeakReference<MapsActivity> MapsActivity;
private Double distance;
ParserTask(MapsActivity mainActivity) {
this.MapsActivity = new WeakReference<>(mainActivity);
}
@Override
protected ArrayList<LatLng> doInBackground(String... jsonData) {
ArrayList<LatLng> routes = null;
points = new ArrayList<>();
JSONObject jObject;
try {
String data = downloadUrl(jsonData[0]);
jObject = new JSONObject(data);
parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
distance = parser.getDistance();
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(ArrayList<LatLng> path) {
if (MapsActivity.get() != null) {
//adapt contents
if (path != null && path.size() > 0 ) {
PolylineOptions lineOptions;
lineOptions = new PolylineOptions();
lineOptions.addAll(path);
lineOptions.width(8);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
MapsActivity.get().mMap.addPolyline(lineOptions);
}
}
}
}
}
**DirectionsJSONParser :**
public class DirectionsJSONParser {
private ArrayList<LatLng> points = new ArrayList<>();
private Double distance = 0.0;
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public ArrayList<LatLng> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<>() ;
JSONArray jRoutes;
JSONArray jLegs;
JSONArray jSteps;
try {
jRoutes = jObject.getJSONArray("routes");
if (jRoutes.length() > 0){
/* Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new ArrayList<>();
/* Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
JSONObject distanceobj = ((JSONObject)jLegs.get(j)).getJSONObject("distance");
Double distancest = distanceobj.getDouble("value");
distance += distancest;
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/* Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
//String polyline = "";
String polyline;
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/* Traversing all points */
for (int l = 0; l < list.size(); l++) {
/*HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng) list.get(l)).latitude));
hm.put("lng", Double.toString(((LatLng) list.get(l)).longitude));
path.add(hm);*/
LatLng latLng = new LatLng(list.get(l).latitude,list.get(l).longitude);
points.add(latLng);
}
}
if(routes.isEmpty())
routes.add(path);
else
routes.set(0, path);
}
}
}
} catch (Exception e){
e.printStackTrace();
}
return points;
}
public Double getDistance() {
return distance;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
I hope it'll help you..!
Assuming the code you gave is correct, replace your code with this. Try it out, I have make some changes
package com.xyz.fragments;
//I didnt not include imports in order to have a smaller post on Stackoverflow
//Based on https://developers.google.com/maps/documentation/android-sdk/map-with-marker
public class IncidentMapFragment extends Fragment implements OnMapReadyCallback {
public static final String TAG = "IncidentMapFragment";
private static IncidentMapFragment incidentMapFragment = null;
public static IncidentMapFragment instance() {
if (incidentMapFragment==null)
{
incidentMapFragment = new IncidentMapFragment();
}
return incidentMapFragment;
}
private MapView mapView;
private static GoogleMap map;
private ProgressBar progressBar;
private SupportMapFragment mapFragment;
public static final int UPDATE_MY_CURRENT_LOCATION = 0;
public static final int UPDATE_MY_TEAMS_CURRENT_LOCATIONS = 1;
public static final int UPDATE_ALL_TEAMS_CURRENT_LOCATIONS = 2;
public static final int UPDATE_ALL_LOCATION_BASED_EVENTS = 3;
private static Context context;
private int MY_DEFINED_ACCESS_COARSE_LOCATION_CALLBACK_RESULT = 1;
private int MY_DEFINED_ACCESS_FINE_LOCATION_CALLBACK_RESULT = 2;
boolean flagCoarseLocation = false;
boolean flagFineLocation = false;
private static CameraPosition cp;
private WamsUnitVehicleUnitRelationshipDao vehicleUnitRelationshipDao = new WamsUnitVehicleUnitRelationshipDaoImpl();
private static WamsUnitVehicleUnitRelationship newVehicleUnitRelationship = null;
private static Bundle bundleOfMarkers = new Bundle();
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.incident_map_fragment, container, false);
context = rootView.getContext();
Bundle bundleOfMarkers = new Bundle();
progressBar = rootView.findViewById(R.id.incident_map_progress_bar);
try {
FragmentManager fm = getActivity().getSupportFragmentManager();
mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.incident_map);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.incident_map, mapFragment).commit();
}
} catch (Exception exc) {
Log.e(TAG, exc.getMessage());
exc.printStackTrace();
}
return rootView;
}
@Override
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
Log.i(TAG,"onActivityCreated()");
newVehicleUnitRelationship = vehicleUnitRelationshipDao.getWamsUnitVehicleUnitRelationship(NgfrApp.getInstance().getUniqueDeviceId());
if (bundle!=null) {
bundleOfMarkers = bundle.getBundle("bundleOfMarkers");
cp = bundle.getParcelable("cp");
}
if (mapFragment!=null) {
mapFragment.getMapAsync(this);
}
}
/*Handler used by outside class such as MqttBroker.
1) UPDATE_MY_CURRENT_LOCATION. When my location service send a update location(lat,long) call updateMarkersOnMap() which creates a new AsyncTask to update teh display
2) UPDATE_MY_TEAMS_CURRENT_LOCATIONS. When the MQTT dservice gets new location(lat,long) call updateMarkersOnMap() which creates a new AsyncTask to update teh display
3) UPDATE_ALL_TEAMS_CURRENT_LOCATIONS, not implemented.
*/
public static final Handler updateIncidentMap = new Handler(Looper.getMainLooper()) {
public void handleMessage(Message msg) {
//if the context is null then the MapFragment & GoogleMap objects are NOT instantiated and updating the maps non-existant UI will cause exceptions, NPE, and crashes!
if (context != null) {
Location myCurrentLocation = null;
final int what = msg.what;
switch (what) {
case UPDATE_MY_CURRENT_LOCATION:
Log.i(TAG,"UPDATE_MY_CURRENT_LOCATION");
myCurrentLocation = (Location) msg.obj;
if (map != null) {
updateMarkersOnMap(map, myCurrentLocation.getLatitude(),myCurrentLocation.getLongitude(),newVehicleUnitRelationship.getWamsId(), newVehicleUnitRelationship.getVehicleUnitId());
}
break;
case UPDATE_MY_TEAMS_CURRENT_LOCATIONS:
Log.i(TAG,"UPDATE_MY_TEAMS_CURRENT_LOCATIONS");
if (map != null) {
WamsLocationMarker wamsLocationMarker = (WamsLocationMarker) msg.obj;
updateMarkersOnMap(map, wamsLocationMarker.getLat(),wamsLocationMarker.getLon(), wamsLocationMarker.getClientId(), wamsLocationMarker.getVehicleId());
//mock team
mockTeam(map, wamsLocationMarker.getLat(),wamsLocationMarker.getLon());
}
break;
case UPDATE_ALL_TEAMS_CURRENT_LOCATIONS:
break;
default:
break;
}
} //end if context is NOt null
} //end handleMessage
};
/*I added the @SuppressLint("MissingPermission") because we are handling this in permissionHelper(getActivity()),
and the IDE is too naive to know*/
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
Log.i(TAG, "onMapReady()");
try {
//remove progress bar
progressBar.setVisibility(GONE);
//initially zoom in my location
map = googleMap;
if (permissionHelper(getActivity()))
{
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setCompassEnabled(true);
}
if (cp != null) {
map.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
cp = null;
}
myResume();
}
catch (NullPointerException exc)
{
exc.printStackTrace();
}
}
private static void updateMarkersOnMap(GoogleMap map,double lat,double log, String id, String vehicleId) {
final GoogleMap _map = map;
final double _lat = lat;
final double _log = log;
final String _id = id;
final String _vehicleId = vehicleId;
new AsyncTask < Void, Void, WamsLocationMarker > () {
boolean update = false;
@Override
protected WamsLocationMarker doInBackground(Void...voids) {
Marker marker = null;
WamsLocationMarker wamsLocationMarker=null;
try {
Log.i(TAG,"async map: "+map);
if (_map != null)
{
Log.i(TAG,_map.toString());
//if the wamsLocationMarker exists, then UPDATE
if (bundleOfMarkers.containsKey(_id)) {
Log.i(TAG,"bundleOfMarkers.containsKey(_id): "+bundleOfMarkers.containsKey(_id));
Log.i(TAG,"update true");
//get from hashmap
wamsLocationMarker = (WamsLocationMarker)bundleOfMarkers.get(_id);
update = true;
} else {
//add to map
//if the ids are equal then this is YOU
wamsLocationMarker = new WamsLocationMarkerFactory().createWamsLocationMarker(_id, _vehicleId, _lat, _log);
Log.i(TAG,"WamsLocationMarker");
Log.i(TAG,"update false");
}
} else {
Log.e(TAG, " updateMarkersOnMap() map is " + _map);
}
}
catch (NullPointerException exc)
{
exc.printStackTrace();
}
return wamsLocationMarker;
}
@Override
protected void onPostExecute(WamsLocationMarker wamsLocationMarker) {
super.onPostExecute(wamsLocationMarker);
try {
if (wamsLocationMarker != null) {
Log.i(TAG,"onPostExecute() update:"+update+",wamsLocationMarker:"+wamsLocationMarker);
if (update) {
Log.i(TAG,"onPostExecute() update:"+update);
//UPDATE wth new lat & long if the markers coordinates have change, else dont redraw, beacuse the draw causes a refresh affect & its also a waste computationally
if (wamsLocationMarker.getMarker().getPosition().latitude != _lat && wamsLocationMarker.getMarker().getPosition().longitude != _log) {
LatLng latLng = new LatLng(_lat, _log);
//UPDATE THE MARKER POSITION
wamsLocationMarker.getMarker().setPosition(latLng);
}
} else {
//ADD A NEW MARKER
Marker marker = _map.addMarker(wamsLocationMarker.getMakerOptions());
Log.i(TAG,"ASYNC MARKER:"+marker.getId());
wamsLocationMarker.setMarker(marker);
bundleOfMarkers.remove(wamsLocationMarker.getClientId());
bundleOfMarkers.putParcelable(wamsLocationMarker.getClientId(), wamsLocationMarker);
}
}
}
catch (NullPointerException exc)
{
exc.printStackTrace();
}
}
}.execute();
}
/*I also tried using onSaveInstanceState & onViewStateRestored. I saved the markers on map in Bundle & put them in parceable.
However I was unable to redraw the map*/
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG,"onSaveInstanceState()");
myPause();
outState.putBundle("bundleOfMarkers", bundleOfMarkers);
outState.putParcelable("cp",cp);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG,"onRestoreInstanceState()");
super.onRestoreInstanceState(savedInstanceState);
bundleOfMarkers = savedInstanceState.getBundle("bundleOfMarkers");
myResume();
}
/*
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
Log.i(TAG,"onViewStateRestored(),savedInstanceState:"+savedInstanceState);
super.onViewStateRestored(savedInstanceState);
}*/
/* @Override
public void onResume() {
super.onResume();
Log.i(TAG,"onResume()");
if (mapFragment!=null) {
mapFragment.getMapAsync(this);
}
newVehicleUnitRelationship = vehicleUnitRelationshipDao.getWamsUnitVehicleUnitRelationship(NgfrApp.getInstance().getUniqueDeviceId());
}*/
/*@Override
public void onPause() {
Log.i(TAG,"onPause()");
super.onPause();
myPause();
}*/
public void myResume() {
Log.i(TAG,"myResume()");
Set<String> keys = bundleOfMarkers.keySet();
WamsLocationMarker wamsLocationMarker = null;
for (String k : keys) {
Log.i(TAG,"key:"+k);
wamsLocationMarker = (WamsLocationMarker) bundleOfMarkers.getParcelable(k);
updateMarkersOnMap(map, wamsLocationMarker.getLat(), wamsLocationMarker.getLon(), wamsLocationMarker.getClientId(), wamsLocationMarker.getVehicleId());
}
}
public void myPause()
{
Log.i(TAG,"myPause()");
if (map!=null) {
//lets get the camera position & markers
cp = map.getCameraPosition();
}
//keys in hashmap
Set<String> keys = IncidentMapFragment.bundleOfMarkers.keySet();
WamsLocationMarker wamsLocationMarker = null;
for (String k : keys) {
wamsLocationMarker = (WamsLocationMarker) IncidentMapFragment.bundleOfMarkers.get(k);
bundleOfMarkers.putParcelable(k,wamsLocationMarker);
}
}
//Just for test - Im mocking some there points to represent other teams mates on the map, this is just for testing
private static void mockTeam(GoogleMap map, double _lat, double _log) {
updateMarkersOnMap(map, _lat+0.001, _log , "mock111111111", newVehicleUnitRelationship.getVehicleUnitId());
updateMarkersOnMap(map,_lat, _log+0.001 ,"mock222222222", newVehicleUnitRelationship.getVehicleUnitId());
updateMarkersOnMap(map, _lat-0.001, _log,"mock33333333", newVehicleUnitRelationship.getVehicleUnitId());
updateMarkersOnMap(map, _lat, _log-0.001,"mock444444444", newVehicleUnitRelationship.getVehicleUnitId());
}
//Ask the user if required & attempt to grant required location services
private boolean permissionHelper(Activity activity) {
String permission = Manifest.permission.ACCESS_COARSE_LOCATION;
int res = getContext().checkCallingPermission(permission);
//if the required coarse & fine permissions are granted then return true else proceed to get the permissions
if (res == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "ACCESS_COARSE_LOCATION GRANTED");
permission = Manifest.permission.ACCESS_FINE_LOCATION;
res = getContext().checkCallingPermission(permission);
if (res == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "ACCESS_FINE_LOCATION GRANTED");
flagFineLocation = true;
} else {
Log.i(TAG, "ACCESS_FINE_LOCATION NOT GRANTED");
}
flagCoarseLocation = true;
}
//prompt user for COARSE location permission. If the user cancel then display toast & navigate back
if (!flagCoarseLocation) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
dialogForCoarsePermission();
} else {
ActivityCompat.requestPermissions(activity,
new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_DEFINED_ACCESS_COARSE_LOCATION_CALLBACK_RESULT);
flagCoarseLocation = true;
}
}
//prompt user for FINE location permission. If the user cancel then display toast & navigate back
if (!flagFineLocation) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.ACCESS_FINE_LOCATION)) {
dialogForFinePermission();
} else {
ActivityCompat.requestPermissions(activity,
new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_DEFINED_ACCESS_FINE_LOCATION_CALLBACK_RESULT);
flagFineLocation = true;
}
}
if (!flagCoarseLocation)
{
Log.i(TAG, "ACCESS_COARSE_LOCATION NOT GRANTED");
}
else
{
Log.i(TAG, "ACCESS_COARSE_LOCATION GRANTED");
}
if (!flagFineLocation)
{
Log.i(TAG, "ACCESS_FINE_LOCATION NOT GRANTED");
}
else
{
Log.i(TAG, "ACCESS_FINE_LOCATION GRANTED");
}
return (flagCoarseLocation && flagFineLocation);
}
private void dialogForCoarsePermission() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
ActivityCompat.requestPermissions(getActivity(),
new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_DEFINED_ACCESS_COARSE_LOCATION_CALLBACK_RESULT);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("The map requires coarse location permission.Please it by pressing Yes. ").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
private void dialogForFinePermission() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
ActivityCompat.requestPermissions(getActivity(),
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_DEFINED_ACCESS_FINE_LOCATION_CALLBACK_RESULT);
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("The map ALSO requires fine location permission.Please it by pressing Yes. ").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
Log.i(TAG, "onRequestPermissionsResult() request code:" + requestCode); // Log printed
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_DEFINED_ACCESS_COARSE_LOCATION_CALLBACK_RESULT) {
flagCoarseLocation = true;
Toast.makeText(context, "Coarse location permission granted.", Toast.LENGTH_SHORT).show();
}
if (requestCode == MY_DEFINED_ACCESS_FINE_LOCATION_CALLBACK_RESULT) {
flagFineLocation = true;
Toast.makeText(context, "Fine location permission granted.", Toast.LENGTH_SHORT).show();
}
}
}
**Fragment Adapter class:**
package com.xyz.views;
//didnt include imports
public class MainActivityViewPagerAdapter extends FragmentStatePagerAdapter {
public MainActivityViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment returnFragment=null;
switch(position) {
case 0:
returnFragment = ServicesFragment.newInstance();
break;
case 1:
returnFragment = BiometricsFragment.newInstance();
break;
case 2:
returnFragment =IncidentMapFragment.newInstance();
break;
}
return returnFragment;
}
@Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position) {
CharSequence title=null;
switch (position) {
case 0:
title = "Services";
break;
case 1:
title = "Biometrics";
break;
case 2:
title = "Incident Map";
break;
}
return title;
}
}