I am using GoogleApiClient to get current location in Service class and while starting I want to get the status of location Service of mobile, if location service is disable then I want to show popup to enable it.
So how do I check the status of location service using GoogleApiClient
here is my Service class
public class MyService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private static final long INTERVAL = 1000 * 300;
private static final long FASTEST_INTERVAL = 1000 * 200;
public MyService() {
super();
}
#Override
public void onCreate() {
super.onCreate();
//initialize location request
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//initialize GooleApiClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
//code to find nearby using TimerTask
Timer timer = new Timer();
TimerTaskFindNearby findNearby = new TimerTaskFindNearby(getApplicationContext());
timer.scheduleAtFixedRate(findNearby,1000,AppDataHandler.TASK_TIME);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
Log.d("Service","onstartcommand");
return Service.START_STICKY;
}
#Override
public void onConnected(Bundle arg0) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else{
onLocationChanged(location);
}
}
#Override
public void onLocationChanged(Location location) {
AppDataHandler.myLocation.setLatitude(String.valueOf(location.getLatitude())+"");
AppDataHandler.myLocation.setLongitude(String.valueOf(location.getLongitude())+"");
//store on shared pref
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("FriendFinderSharedPref", Context.MODE_PRIVATE);
LocationBean myLocation = new LocationBean();
myLocation.setLatitude(String.valueOf(location.getLatitude())+"");
myLocation.setLongitude(String.valueOf(location.getLongitude())+"");
myLocation.setMobile(sharedPreferences.getString("myMobile", "noData"));
//save to shared pref to make accessible from TimerTask
Gson gson = new Gson();
Editor editor = sharedPreferences.edit();
editor.putString("myLocation", gson.toJson(myLocation).toString());
editor.commit();
//store location on server by using volley String request
String url = baseURL+"userdata/savemylocation";
//inform to activity
sendBroadcast();
}
//send broadcast from activity to all receivers listening to the action "ACTION_STRING_ACTIVITY"
private void sendBroadcast() {
final Intent new_intent = new Intent();
new_intent.setAction(AppDataHandler.ACTIVITY_RECEIVER_ACTION);
sendBroadcast(new_intent);
}
#Override
public void onDestroy() {
Log.d("service", "destroy");
super.onDestroy();
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {}
#Override
public void onConnectionSuspended(int arg0) {}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
//final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
//...
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
getActivity(),
REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
//...
break;
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d("onActivityResult()", Integer.toString(resultCode));
//final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode)
{
case REQUEST_LOCATION:
switch (resultCode)
{
case Activity.RESULT_OK:
{
// All required changes were successfully made
Toast.makeText(getActivity(), "Location enabled by user!", Toast.LENGTH_LONG).show();
break;
}
case Activity.RESULT_CANCELED:
{
// The user was asked to change settings, but chose not to
Toast.makeText(getActivity(), "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
break;
}
default:
{
break;
}
}
break;
}
}
This will display a dialog if location is OFF
I know this is too late but you can use this function :
private boolean checkPlayServices() {
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
finish();
return false;
}
return true;
}
Related
I am trying to fetch users last known location after user clicks OK on enable location dialog.Someone please let me know where should i need to implement get last known location functionality.
Below is my code:
public class BrodReceiver extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener{
LinearLayout linear;
GoogleApiClient mGoogleApiClient;
private static final String BROADCAST_ACTION = "android.location.PROVIDERS_CHANGED";
private static final int ACCESS_FINE_LOCATION_INTENT_ID = 3;
private static final int REQUEST_CHECK_SETTINGS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_brod_receiver);
linear = findViewById(R.id.linear);
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
checkPermissions();
}
#Override
protected void onStop() {
super.onStop();
if(mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
private void checkPermissions(){
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(BrodReceiver.this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
requestLocationPermission();
else
showSettingDialog();
} else
showSettingDialog();
}
private void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(BrodReceiver.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(BrodReceiver.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION_INTENT_ID);
} else {
ActivityCompat.requestPermissions(BrodReceiver.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION_INTENT_ID);
}
}
private void showSettingDialog(){
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);//5 sec Time interval for location update
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
final LocationSettingsStates state = locationSettingsResult.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Toast.makeText(getApplicationContext(),"GPS activated",Toast.LENGTH_SHORT).show();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(BrodReceiver.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch(requestCode){
case REQUEST_CHECK_SETTINGS:
switch(resultCode){
case RESULT_OK:
Log.e("Settings", "Result OK");
Toast.makeText(getApplicationContext(),"GPS enabled",Toast.LENGTH_SHORT).show();
//startLocationUpdates();
break;
case RESULT_CANCELED:
Log.e("Settings", "Result Cancel");
Toast.makeText(getApplicationContext(),"GPS disabled",Toast.LENGTH_SHORT).show();
break;
}
break;
}
}
}
After launching app it shows something like this
After clicking OK I want to fetch user last known location.Someone please let me know how to achieve the same.
THANKS
new AlertDialog.Builder(this)
.setCancelable(false)
.setMessage("to continue, turn on device location, which uses Google's location service")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, this);
Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return l;
}
})
.setNegativeButton("NO THANKS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
})
.create()
.show();
for API levels > 23, you must ask for runtime permissions before you can get the users last known location
I want to start a service which opens GPS dialogue if it is off on device boot process. I have a broadcast receiver on boot then I trigger this service to open dialogue without opening the main application.I am using service, in service I need to call GPS location dialogue box to turn on if disable.
public class GPSTestService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener ,VolleyResultCallBack {
private boolean ContinueConnection = true;
LocationRequest mLocationRequest;
public static GoogleApiClient mGoogleApiClient;
PendingResult<LocationSettingsResult> result;
final static int REQUEST_LOCATION = 199;
Context contex;
#Override
public void onVolleyErrorListener(VolleyError error) {
}
#Override
public void onVolleyResultListener(Context mContext, JSONArray response) {
}
#Override
public void onCreate() {
super.onCreate();
contex=getApplicationContext();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
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.
Toast.makeText(getApplicationContext(), "GPSTestService", Toast.LENGTH_SHORT).show();
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult((Activity) contex, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
//...
break;
}
}
});
}
#Override
public void onConnectionSuspended(int i) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Utils.getInstance().syncData(this,this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
return Service.START_NOT_STICKY;
}
}
I have an issue with status.startResolutionForResult((Activity) context, REQUEST_LOCATION); how to deal it in service? as we can not pass activity here.
in service I need to call GPS location dialogue box to turn on if disable
That is not possible, sorry. Do that work in your activity before starting the service. If the service detects that the user disabled location access while the service is running, the service can raise a Notification which leads the user to an activity where you can request GPS access.
i want to switched on location like OLA cab so i am using this code:
private GoogleApiClient googleApiClient;final static int REQUEST_LOCATION = 199;public boolean noLocation() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// buildAlertMessageNoGps();
enableLoc();
return true;
}
return false;
}private void enableLoc() {if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Timber.v("Location error " + connectionResult.getErrorCode());
}
}).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
(Activity) context, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_LOCATION:
switch (resultCode) {
case Activity.RESULT_CANCELED: {
finish();
break;
}
default: {
break;
}
}
break;
}
}
now it is working fine but i want to disable location using dialog, don't want to use intent for open setting screen.How is it possible?
Query 1 :I am checking user's location at the splash screen if location is not enabled the there is a prompt that will enable user's location without leaving the app. but when the prompt displayed it is not waiting for user's response (yes/no). for this i have to handle the prompt result into some method so that according to the user's response rest of the code will execute. i have tried this using onActivityresult() method but no luck because first it requires to call startActivityForResult()and it takes the intent as one of its parameter( in my code there is no need for user to navigation phone location setting once user will say yes location will enable automatically). i want to execute the code after user click yes.
Query2 when the dialog box displayed i want the splash screen to run in backgroud.
splash screen
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
bundle = getIntent().getExtras();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Boolean b1= locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
LocationManager locationManager1 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Boolean b2=locationManager1.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!b1&&!b2) {
startLocationAlert = new StartLocationAlert(this);
Boolean b3=startLocationAlert.settingsrequest();
} else {
startActivityThread();
}
}
public void startActivityThread(){
final Thread thread = new Thread() {
#Override
public void run() {
super.run();
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = null;
boolean loggedIn = false;
SharedPreferences w = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor share = w.edit();
loggedIn = (w.getBoolean("loggedIn", loggedIn));
System.out.println("logged in " + loggedIn);
if (loggedIn) {
intent = new Intent(SplashScreen.this, TestNavigationFragments.class);
} else {
intent = new Intent(SplashScreen.this, Login.class);
}
startActivity(intent);
finish();
}
}
};
thread.start();
}
StartLocationAlert
Activity context;
boolean result1=false;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
GoogleApiClient googleApiClient;
public StartLocationAlert(Activity context) {
this.context = context;
googleApiClient = getInstance();
if(googleApiClient != null){
settingsrequest();
googleApiClient.connect();
result1=true;
}
}
public GoogleApiClient getInstance(){
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
return mGoogleApiClient;
}
public boolean settingsrequest()
{
Log.e("settingsrequest","Comes");
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, 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:
result1=true;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.e("Applicationsett",e.toString());
}
result1=true;
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Toast.makeText(context, "Location is Enabled", Toast.LENGTH_SHORT).show();
result1=true;
break;
}
}
});
return result1;
}
I am using this code to for user to activate the location services. I want to show user dialog to accept to enable location services then redirect them to the LOCATION_SETTINGS Page. But Without the user accepting it from user it redirects to location settings.
if(lm==null)
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
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){
dialog = new AlertDialog.Builder(this);
dialog.setMessage(this.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(this.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);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(this.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
finish();
}
});
dialog.show();
}
As far as I understand you try to enable the location.
You can show a dialog to enable the location instead of redirect them to LOCATION_SETTING page.
Step by step process.
First you need to set a GoogleApiClient and implements GoogleApiClient CallBackMethods.
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
CallBack Methods
#Override
public void onConnected(Bundle bundle) {
Log.d("OnConnected", "Connection successful");
settingsrequest();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
As soon as the googleapiclient connects, onconnected method will invoke and settingsRequest method will call.
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
LocationRequest locationRequest;
public void settingsrequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setNumUpdates(1);
locationRequest.setExpirationDuration(20000);
locationRequest.setFastestInterval(500);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true); //this is the key ingredient
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS: {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
}
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(MainTab.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
status.startResolutionForResult(MainTab.this, REQUEST_CHECK_SETTINGS) will show a dialog requesting location.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
break;
case Activity.RESULT_CANCELED:
break;
}
break;
}
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this) will set a listener for the location cahnged.
As the location changed onLocationChanged method will invoke.
#Override
public void onLocationChanged(Location location) {
prevLocation = location;
//Do you work
}
Hope this will helps you.