In Our application we want to integrate the android Default GPS Dialog. The same dialog that appears when the GPS is OFF and we press of my location button in google map apps. Have also attached the image of the dialog which I want to integrate.
在我们的应用程序中,我们想要集成Android默认GPS对话框。 GPS关闭时出现的同一个对话框,我们在谷歌地图应用程序中按下我的位置按钮。还附上了我要整合的对话框的图像。
- Clicking on "No" option will close the dialog.
- Clicking on "Yes" option will Activate the GPS of device directly.
单击“否”选项将关闭对话框。
单击“是”选项将直接激活设备的GPS。
Dialog the appears for OLA app Below (ANDROID L):
对话框出现在OLA app下面(ANDROID L):
Dialog the appears for OLA app Below (ANDROID KIT_KAT):
为OLA应用程序显示对话框(ANDROID KIT_KAT):
Dialog the appears for Google Map Below (ANDROID L):
对话框出现在谷歌地图下面(ANDROID L):
Our existing implementation is when the GPS is OFF we are redirecting application to the default location setting screen of the device from where he/she can turn ON the Location.
我们现有的实施方案是当GPS关闭时,我们将应用程序重定向到设备的默认位置设置屏幕,他/她可以从该位置打开位置。
looking forward for answers. Thanks in advance.
期待着答案。提前致谢。
4 个解决方案
#1
You need to use the latest version of Google Play service. latest version has one dialog to activate all required things to get the GPS.
您需要使用最新版本的Google Play服务。最新版本有一个对话框,可以激活所有需要的东西来获取GPS。
From Android Developer Play Service documentation,
来自Android Developer Play Service文档,
Location settings - While the FusedLocationProviderApi combines multiple sensors to give you the optimal location, the accuracy of the location your app receives still depends greatly on the settings enabled on the device (GPS, wifi, airplane mode, and others). Using the new SettingsApi class, you can bring up a Location Settings dialog which displays a one-touch control for users to change their settings without leaving your app.
位置设置 - 虽然FusedLocationProviderApi结合了多个传感器以提供最佳位置,但应用程序接收位置的准确性仍然在很大程度上取决于设备上启用的设置(GPS,wifi,飞行模式等)。使用新的SettingsApi类,您可以打开一个“位置设置”对话框,该对话框显示一键式控件,用户无需离开您的应用即可更改其设置。
Link directs to Play Service version documentation. Version 7.0 has introduced this new prompt.
链接指向Play服务版本文档。 7.0版引入了这个新提示。
#2
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
public class LocSettingsActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback {
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest locationRequest;
int REQUEST_CHECK_SETTINGS = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc_settings);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
builder.build()
);
result.setResultCallback(this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// NO need to show the dialog;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. Show the user a dialog
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(LocSettingsActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
//failed to show
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are unavailable so not possible to show any dialog now
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.google.android.gms:play-services-location:8.4.0'
}
#3
Ola Cabs is using the newly released Settings API to achieve this functionality. As per the new API the user is not required to navigate to the settings page to enable location services giving a seamless integration for the same. Please read this for more details.
Ola Cabs正在使用新发布的Settings API来实现此功能。根据新API,用户无需导航到设置页面即可启用位置服务,从而实现无缝集成。请阅读此内容以获取更多详情。
#4
Step By Step
一步步
Step 1 check hasGPSDevice Support or not
步骤1检查hasGPSDevice支持与否
Step 2 hasGPSDevice true check MarshMallow Permimssion
第2步hasGPSDevice真实检查MarshMallow Permimssion
Step 3 MarshMallow Permimssion true check Location already on or not
第3步MarshMallow Permimssion真实检查位置是否已经开启
Step 4 If Location on then CAll Gps Tracker and fetch Lat Long
步骤4如果位置在CAll Gps Tracker上并获取Lat Long
Step 5 If Location oFf then CAll Location Dialog same AS Google Maps
步骤5如果位置oFf然后CAll位置对话与AS谷歌地图相同
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUMnVLTGpWcTk2QUE
Add Dependency and Internet Permission
添加依赖关系和Internet权限
compile 'com.google.android.gms:play-services-location:8.4.0'
package com.keshav.locationenabledorcancelwithoutoutsideclick;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.keshav.locationenabledorcancelwithoutoutsideclick.gps.GPSTracker;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class LocSettingsActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback {
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest locationRequest;
int REQUEST_CHECK_SETTINGS = 100;
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Step 1
checkPermission();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
builder.build()
);
result.setResultCallback(this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
// public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
public void onResult(@NonNull Result locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// NO need to show the dialog;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. Show the user a dialog
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(LocSettingsActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
//failed to show
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are unavailable so not possible to show any dialog now
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
Log.e("Keshav", "..........GPS enabled..............");
//TODO Important When Gps Enable Just Now Need Some Time ..........otherwise lat long 0.0 fetch
// TODO Need Some time to call GPS Tracker Service
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000); //Todo dummy delay for 2 second
} catch (InterruptedException e) {
e.printStackTrace();
}
//update ui on UI thread
runOnUiThread(new Runnable() {
@Override
public void run() {
callLocationGpsTracker();
}
});
}
}).start();
} else {
callLocationDialog();
Log.e("Keshav", "..........GPS not enabled..............");
Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
private void checkPermission(){
if (!hasGPSDevice(LocSettingsActivity.this)) {
Log.e("keshav", "Gps not Supported");
Toast.makeText(LocSettingsActivity.this, "Gps not Supported", Toast.LENGTH_SHORT).show();
} else {
Log.e("keshav", "Gps Supported ---hasGPSDevice return true--Step 1 Pass...........");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(LocSettingsActivity.this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Log.e("permission", "granted");
locationEnabled_or_Not();
} else {
ActivityCompat.requestPermissions(LocSettingsActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
}
} else {
Log.e("MainActivity", "Lower Than MarshMallow");
locationEnabled_or_Not();
}
}
}
//TODO Step 1
public boolean hasGPSDevice(Context context) {
final LocationManager mgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
if (mgr == null)
return false;
final List<String> providers = mgr.getAllProviders();
if (providers == null)
return false;
return providers.contains(LocationManager.GPS_PROVIDER);
}
//TODO Step 2
// TODO When Location not enabled show popup
// TODO When Location already Enabled CAll GPS Tracker
private void locationEnabled_or_Not() {
Log.e("keshav", "locationEnabled_or_Not Step 2 Pass...........");
final LocationManager manager = (LocationManager) LocSettingsActivity.this.getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocSettingsActivity.this)) {
Log.e("keshav", "Gps not enabled");
callLocationDialog();
} else {
Log.e("keshav", "Gps already enabled");
callLocationGpsTracker(); // TODO When Gps already enabled call direct GPS Tracker
}
}
//TODO Step 3 when hasGPSDevice return true
private void callLocationDialog() {
Log.e("keshav", "callLocationDialog Step 3 Popup called ...........");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
}
//TODO Step 4 when location on fetch GPS Tracker Through Latitude Longitude
private void callLocationGpsTracker() {
Log.e("keshav", "callLocationGpsTracker Step 4 Called ... fetch Location");
gps = new GPSTracker(LocSettingsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.e("MainActivity", "latitude -> " + latitude);
Log.e("MainActivity", "longitude -> " + longitude);
getAddress(latitude, longitude);
// LocationAddress locationAddress = new LocationAddress();
// locationAddress.getAddressFromLocation(latitude, longitude,
// getApplicationContext(), new GeocoderHandler());
} else {
// TODO can't get location
// TODO GPS or Network is not enabled
// TODO Ask user to enable GPS/network in settings
//TODO need again call Locaton Dialog
callLocationDialog();
}
}
private void getAddress(double lat, double lon) {
String cityName = "";
String stateName = "";
String postalCode = "";
String countryName = "";
StringBuilder finalAddress = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(LocSettingsActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses != null) {
try {
cityName = addresses.get(0).getLocality();
stateName = addresses.get(0).getAdminArea();
countryName = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
if (addresses.get(0).getAddressLine(0) != null)
finalAddress.append(addresses.get(0).getAddressLine(0));
if (addresses.get(0).getAddressLine(1) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(1));
if (addresses.get(0).getAddressLine(2) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(2));
if (addresses.get(0).getAddressLine(3) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(3));
Log.e("keshav", "addres 0 -> " + addresses.get(0).getAddressLine(0));
Log.e("keshav", "addres 1 -> " + addresses.get(0).getAddressLine(1));
Log.e("keshav", "addres 2 -> " + addresses.get(0).getAddressLine(2));
Log.e("keshav", "addres 3 -> " + addresses.get(0).getAddressLine(3));
Log.e("keshav", "addres final -> " + finalAddress);
} catch (Exception e) {
Log.e("keshav", "Exception occurd -> " + e.getMessage());
e.printStackTrace();
}
Log.e("keshav", "cityName -> " + cityName);
Log.e("keshav", "stateName -> " + stateName);
Log.e("keshav", "countryName -> " + countryName);
Log.e("keshav", "PostalCode -> " + postalCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
checkPermission();
}
}
===============================GPSTracker===================================
package com.keshav.locationenabledorcancelwithoutoutsideclick.gps;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* @return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUMnVLTGpWcTk2QUE
#1
You need to use the latest version of Google Play service. latest version has one dialog to activate all required things to get the GPS.
您需要使用最新版本的Google Play服务。最新版本有一个对话框,可以激活所有需要的东西来获取GPS。
From Android Developer Play Service documentation,
来自Android Developer Play Service文档,
Location settings - While the FusedLocationProviderApi combines multiple sensors to give you the optimal location, the accuracy of the location your app receives still depends greatly on the settings enabled on the device (GPS, wifi, airplane mode, and others). Using the new SettingsApi class, you can bring up a Location Settings dialog which displays a one-touch control for users to change their settings without leaving your app.
位置设置 - 虽然FusedLocationProviderApi结合了多个传感器以提供最佳位置,但应用程序接收位置的准确性仍然在很大程度上取决于设备上启用的设置(GPS,wifi,飞行模式等)。使用新的SettingsApi类,您可以打开一个“位置设置”对话框,该对话框显示一键式控件,用户无需离开您的应用即可更改其设置。
Link directs to Play Service version documentation. Version 7.0 has introduced this new prompt.
链接指向Play服务版本文档。 7.0版引入了这个新提示。
#2
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
public class LocSettingsActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback {
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest locationRequest;
int REQUEST_CHECK_SETTINGS = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc_settings);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
builder.build()
);
result.setResultCallback(this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// NO need to show the dialog;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. Show the user a dialog
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(LocSettingsActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
//failed to show
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are unavailable so not possible to show any dialog now
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
}
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.google.android.gms:play-services-location:8.4.0'
}
#3
Ola Cabs is using the newly released Settings API to achieve this functionality. As per the new API the user is not required to navigate to the settings page to enable location services giving a seamless integration for the same. Please read this for more details.
Ola Cabs正在使用新发布的Settings API来实现此功能。根据新API,用户无需导航到设置页面即可启用位置服务,从而实现无缝集成。请阅读此内容以获取更多详情。
#4
Step By Step
一步步
Step 1 check hasGPSDevice Support or not
步骤1检查hasGPSDevice支持与否
Step 2 hasGPSDevice true check MarshMallow Permimssion
第2步hasGPSDevice真实检查MarshMallow Permimssion
Step 3 MarshMallow Permimssion true check Location already on or not
第3步MarshMallow Permimssion真实检查位置是否已经开启
Step 4 If Location on then CAll Gps Tracker and fetch Lat Long
步骤4如果位置在CAll Gps Tracker上并获取Lat Long
Step 5 If Location oFf then CAll Location Dialog same AS Google Maps
步骤5如果位置oFf然后CAll位置对话与AS谷歌地图相同
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUMnVLTGpWcTk2QUE
Add Dependency and Internet Permission
添加依赖关系和Internet权限
compile 'com.google.android.gms:play-services-location:8.4.0'
package com.keshav.locationenabledorcancelwithoutoutsideclick;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.keshav.locationenabledorcancelwithoutoutsideclick.gps.GPSTracker;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class LocSettingsActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback {
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest locationRequest;
int REQUEST_CHECK_SETTINGS = 100;
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Step 1
checkPermission();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
builder.build()
);
result.setResultCallback(this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
// public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
public void onResult(@NonNull Result locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// NO need to show the dialog;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. Show the user a dialog
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(LocSettingsActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
//failed to show
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are unavailable so not possible to show any dialog now
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
Log.e("Keshav", "..........GPS enabled..............");
//TODO Important When Gps Enable Just Now Need Some Time ..........otherwise lat long 0.0 fetch
// TODO Need Some time to call GPS Tracker Service
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000); //Todo dummy delay for 2 second
} catch (InterruptedException e) {
e.printStackTrace();
}
//update ui on UI thread
runOnUiThread(new Runnable() {
@Override
public void run() {
callLocationGpsTracker();
}
});
}
}).start();
} else {
callLocationDialog();
Log.e("Keshav", "..........GPS not enabled..............");
Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
private void checkPermission(){
if (!hasGPSDevice(LocSettingsActivity.this)) {
Log.e("keshav", "Gps not Supported");
Toast.makeText(LocSettingsActivity.this, "Gps not Supported", Toast.LENGTH_SHORT).show();
} else {
Log.e("keshav", "Gps Supported ---hasGPSDevice return true--Step 1 Pass...........");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(LocSettingsActivity.this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Log.e("permission", "granted");
locationEnabled_or_Not();
} else {
ActivityCompat.requestPermissions(LocSettingsActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
}
} else {
Log.e("MainActivity", "Lower Than MarshMallow");
locationEnabled_or_Not();
}
}
}
//TODO Step 1
public boolean hasGPSDevice(Context context) {
final LocationManager mgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
if (mgr == null)
return false;
final List<String> providers = mgr.getAllProviders();
if (providers == null)
return false;
return providers.contains(LocationManager.GPS_PROVIDER);
}
//TODO Step 2
// TODO When Location not enabled show popup
// TODO When Location already Enabled CAll GPS Tracker
private void locationEnabled_or_Not() {
Log.e("keshav", "locationEnabled_or_Not Step 2 Pass...........");
final LocationManager manager = (LocationManager) LocSettingsActivity.this.getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocSettingsActivity.this)) {
Log.e("keshav", "Gps not enabled");
callLocationDialog();
} else {
Log.e("keshav", "Gps already enabled");
callLocationGpsTracker(); // TODO When Gps already enabled call direct GPS Tracker
}
}
//TODO Step 3 when hasGPSDevice return true
private void callLocationDialog() {
Log.e("keshav", "callLocationDialog Step 3 Popup called ...........");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
}
//TODO Step 4 when location on fetch GPS Tracker Through Latitude Longitude
private void callLocationGpsTracker() {
Log.e("keshav", "callLocationGpsTracker Step 4 Called ... fetch Location");
gps = new GPSTracker(LocSettingsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.e("MainActivity", "latitude -> " + latitude);
Log.e("MainActivity", "longitude -> " + longitude);
getAddress(latitude, longitude);
// LocationAddress locationAddress = new LocationAddress();
// locationAddress.getAddressFromLocation(latitude, longitude,
// getApplicationContext(), new GeocoderHandler());
} else {
// TODO can't get location
// TODO GPS or Network is not enabled
// TODO Ask user to enable GPS/network in settings
//TODO need again call Locaton Dialog
callLocationDialog();
}
}
private void getAddress(double lat, double lon) {
String cityName = "";
String stateName = "";
String postalCode = "";
String countryName = "";
StringBuilder finalAddress = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(LocSettingsActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses != null) {
try {
cityName = addresses.get(0).getLocality();
stateName = addresses.get(0).getAdminArea();
countryName = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
if (addresses.get(0).getAddressLine(0) != null)
finalAddress.append(addresses.get(0).getAddressLine(0));
if (addresses.get(0).getAddressLine(1) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(1));
if (addresses.get(0).getAddressLine(2) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(2));
if (addresses.get(0).getAddressLine(3) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(3));
Log.e("keshav", "addres 0 -> " + addresses.get(0).getAddressLine(0));
Log.e("keshav", "addres 1 -> " + addresses.get(0).getAddressLine(1));
Log.e("keshav", "addres 2 -> " + addresses.get(0).getAddressLine(2));
Log.e("keshav", "addres 3 -> " + addresses.get(0).getAddressLine(3));
Log.e("keshav", "addres final -> " + finalAddress);
} catch (Exception e) {
Log.e("keshav", "Exception occurd -> " + e.getMessage());
e.printStackTrace();
}
Log.e("keshav", "cityName -> " + cityName);
Log.e("keshav", "stateName -> " + stateName);
Log.e("keshav", "countryName -> " + countryName);
Log.e("keshav", "PostalCode -> " + postalCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
checkPermission();
}
}
===============================GPSTracker===================================
package com.keshav.locationenabledorcancelwithoutoutsideclick.gps;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* @return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Source Code
https://drive.google.com/open?id=0BzBKpZ4nzNzUMnVLTGpWcTk2QUE