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.
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
So I am trying to make an app in Android Studio which needs location settings turned on and therefor I wanted to make that window pop up in onCreate that asks if you would like to turn on location settings. But after you press Abort I dont know how to bring that window back again...
Is there a way to do so? Because I have seen in some apps like Tinder, that they won't start until you have pressed a few times on the Abort button.
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
PendingResult<LocationSettingsResult> result;
final static int REQUEST_LOCATION = 199;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(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();
Log.d("Status: ", result.toString());
//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(
MainActivity.this,
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) + "," + Integer.toBinaryString(requestCode));
switch (requestCode)
{
case REQUEST_LOCATION:
switch (resultCode)
{
case Activity.RESULT_OK:
{
// All required changes were successfully made
Toast.makeText(MainActivity.this, "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(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
break;
}
default:
{
break;
}
}
break;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
Create methode
private void mGoogleApiClientConnect(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
and call it here :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClientConnect();
}
and here :
case Activity.RESULT_CANCELED:
{
Toast.makeText(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
mGoogleApiClient.connect();
break;
}
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?
So I notice Google Map was able to prompt the user to enable the GPS. I tried this method below and I got the prompt once and then nothing... Why aren't the onActivityResult() method isn't called anymore?
public void checkLocationEnable() {
Log.e(TAG, "Here");
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
final 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();
Log.e(TAG, "state:" + state);
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.e(TAG, "HERE-1");
// All location settings are satisfied. The client can
// initialize location requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.e(TAG, "REQUIRED");
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
getActivity(),
GenericActivity.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.
Log.e(TAG, "UNAVALAIBLE");
break;
}
}
});
}
As far as I understand you try to enable the location.
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.
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;
}