如何在Android上以编程方式启用或禁用GPS?


158

我知道关于在Android 编程方式打开/关闭GPS的问题已经讨论了 很多 ,答案始终是相同的:

“出于安全/隐私原因,您不能,必须转到位置首选项屏幕,然后让用户启用/禁用它。”

我了解,但是我最近是从市场上购买Tasker的,除此以外,您还可以设置规则以在进入预定应用程序时自动启用GPS并在退出时将其禁用(请参见此处,有关如何执行此操作的教程,它就可以使用!),此应用无法使用固件签名密钥进行签名,因为它可以在许多android版本和不同的设备上使用,甚至不需要扎根。

我想在我的应用程序中执行此操作。当然,我不想破坏用户的隐私,因此我首先会询问用户是否要使用典型的“记住我的决定”复选框自动打开它,如果他回答是,请启用它。

是否有人对Tasker如何实现这一目标有任何想法或线索?

Answers:


161

利用电源管理器小部件中的错误可以切换GPS 。请参阅此xda线程进行讨论。

这是我使用的一些示例代码

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

使用以下命令测试电源控制小部件的现有版本是否为可切换gps的版本。

private boolean canToggleGPS() {
    PackageManager pacman = getPackageManager();
    PackageInfo pacInfo = null;

    try {
        pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        return false; //package not found
    }

    if(pacInfo != null){
        for(ActivityInfo actInfo : pacInfo.receivers){
            //test if recevier is exported. if so, we can toggle GPS.
            if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                return true;
            }
        }
    }

    return false; //default
}

4
在发表此(我)评论时,此答案中的链接似乎表明该漏洞利用的错误已得到修复。我只是想指出,该漏洞利用程序在我自己的测试环境中似乎仍然可以正常工作,因此您不应该放弃尝试此方法……只要确保您的代码能够处理任何错误即可!
SilithCrowe 2011年

1
在撰写本文时,此漏洞利用仍可在2.2.1 Android手机上使用。很好,Ben H.
Qix-蒙尼卡失踪了2011年

38
这真是个坏主意。错误修复后,您的利用将不再起作用。最好只是将用户发送到设置应用。
爱德华·福尔克

1
在Android 2.3.6上可以正常工作,但在android 4.0.3下不能正常工作。任何在Android 4.0.3中启用或禁用的想法
克里希纳

5
哈哈哈...这个漏洞在4.2.2中重新出现,很惊讶地看到它。
amithgc

70

现在不允许所有这些答案。这是正确的:

对于所有仍在寻找答案的人:

这是OLA Cabs和其他此类应用程序的运行方式。

将此添加到您的onCreate中

if (googleApiClient == null) {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(Login.this).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); // 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:
                // 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(Login.this, 1000);
                } 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 onConnected(Bundle arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

这是相同的Android文档

如果其他人仍在挣扎,这可以帮助他们:

编辑添加Irfan Raza的评论以获取更多帮助。

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == 1000) {
         if(resultCode == Activity.RESULT_OK){
             String result=data.getStringExtra("result"); 
         } if (resultCode == Activity.RESULT_CANCELED) {
             //Write your code if there's no result 
         } 
    } 
} 

现在,这个答案应该可以接受了。非常感谢Akshat!
Gurpreet

2
需要Google API客户端集成,因此仅是针对特定用例的解决方案,而不适合通用解决方案。
Cik

@DilroopSingh您遇到了什么问题?我正在使用相同的代码,它运行完美。
Akshat

1
我们能在不显示builder的情况下实现这一目标吗?因为我需要打开gps而不显示任何警报。
Punithapriya

3
@Punithapriya那不可能。必须征得用户同意,因此必须显示构建器。
Akshat

50

启用GPS:

Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);

停用GPS:

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);

1
GPS会自动打开/关闭。
调试器2012年

1
这也有助于启用。私人无效turnGPSOn(){字符串提供程序= Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(!provider.contains(“ gps”)){//如果禁用了gps,则最终Intent戳= new Intent(); poke.setClassName(“ com.android.settings”,“ com.android.settings.widget.SettingsAppWidgetProvider”); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse(“ 3”)); sendBroadcast(戳); }
调试器2012年

在asamsung sII上运行的android 2.3.4中,它会在没有有效激活gps传感器的情况下打开gps图标。但是,如果您选择以编程方式打开GPS传感器,则它将被识别。
tony gil 2012年

24
android 4.0.4-仅启用gps 通知。不是GPS本身。所以看起来好像是开着,但实际上不是
。– alex

14
java.lang.SecurityException:权限拒绝:不允许发送广播android.location.GPS_ENABLED_CHANGE
Abhi

28

如果将应用程序移至此代码可在ROOTED手机上使用 /system/aps并且它们在清单中具有以下权限

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>

private void turnGpsOn (Context context) {
    beforeEnable = Settings.Secure.getString (context.getContentResolver(),
                                              Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    String newSet = String.format ("%s,%s",
                                   beforeEnable,
                                   LocationManager.GPS_PROVIDER);
    try {
        Settings.Secure.putString (context.getContentResolver(),
                                   Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                                   newSet); 
    } catch(Exception e) {}
}


private void turnGpsOff (Context context) {
    if (null == beforeEnable) {
        String str = Settings.Secure.getString (context.getContentResolver(),
                                                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (null == str) {
            str = "";
        } else {                
            String[] list = str.split (",");
            str = "";
            int j = 0;
            for (int i = 0; i < list.length; i++) {
                if (!list[i].equals (LocationManager.GPS_PROVIDER)) {
                    if (j > 0) {
                        str += ",";
                    }
                    str += list[i];
                    j++;
                }
            }
            beforeEnable = str;
        }
    }
    try {
        Settings.Secure.putString (context.getContentResolver(),
                                   Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                                   beforeEnable);
    } catch(Exception e) {}
}

5
+1表示此方法。它也应该与非root用户的设备上的系统应用程序一起使用。
AlexS

这是正确的方法。适用于所有版本的Android,无需任何技巧!
BQuadra

关闭GPS是行不通的!您能告诉我原因和可能的解决方法吗?
Shivansh 2014年

现在,GPS可以完全打开和关闭,但GPS无法正常工作,即给定位长点0.0
Shivansh

<uses-permission android:name =“ android.permission.WRITE_SECURE_SETTINGS” />仅适用于系统aps
sijo jose 2015年

23

无需使用Intent Settings.ACTION_LOCATION_SOURCE_SETTINGS,您可以直接单击“确定”按钮,在Google Map和Gps之类的应用中显示弹出窗口,而无需重定向到设置,只需使用我的代码即可

注意:如果未打开“位置”,则此行代码会自动打开对话框。这条线也用在Google Map中

 public class MainActivity extends AppCompatActivity
    implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {


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();
            //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 (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(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) {

}
} 

注意:如果未打开“位置”,则此行代码会自动打开对话框。这条线也用在Google Map中


1
此代码工作正常,但不要在gradle文件中忘记位置权限和playservice jar ...
Akash pasupathi

22

从Android 4.4版开始,您无法以编程方式启用/禁用gps。如果您尝试此答案中建议的代码,将触发异常。

java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE

2
那么这是一个评论,还是有解决方案?
Shylendra Madda '17

@Shylendra Madda没有启用GPS的解决方案。您只能调用相应的系统对话框。
令人难以置信的

6

要以编程方式打开或关闭GPS,您需要“ root”访问权限并安装BusyBox。即使有了这些,任务也不是简单的。

示例在这里:Google云端硬盘Github Sourceforge

已在2.3.5和4.1.2 Android上测试。


样品不再可用。
android开发人员

这是最新的:rapidshare.com/files/1458124346/GPSToggler-20130222.7z 我意外删除了旧版本。不再需要BusyBox。
OGP

仍然不可用。也许使用其他文件上传服务?
android开发人员

我公开了该文件夹并进行了验证。现在可以下载了。也是我这里的私人FTP :StackExchange:se@oldgopher.gotdns.com
OGP


5

上面的正确答案很旧,需要新的东西,所以这里是答案

与上次更新一样,我们具有androidx支持,因此请首先在应用程序级别的build.gradle文件中包含依赖项

implementation 'com.google.android.gms:play-services-location:17.0.0'

然后添加您的清单文件:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

如果您要发布,请不要忘记征得用户对这些权限的同意

现在这里是代码,只需使用它

 protected void createLocationRequest() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    SettingsClient client = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());



    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...

            Toast.makeText(MainActivity.this, "Gps already open", 
                                          Toast.LENGTH_LONG).show();
            Log.d("location settings",locationSettingsResponse.toString());
        }
    });

    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                // 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().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MainActivity.this,
                            REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                }
            }
        }
    });
}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==REQUEST_CHECK_SETTINGS){

        if(resultCode==RESULT_OK){

            Toast.makeText(this, "Gps opened", Toast.LENGTH_SHORT).show();
            //if user allows to open gps
            Log.d("result ok",data.toString());

        }else if(resultCode==RESULT_CANCELED){

            Toast.makeText(this, "refused to open gps", 
                                         Toast.LENGTH_SHORT).show();
            // in case user back press or refuses to open gps
            Log.d("result cancelled",data.toString());
        }
    }
}

如果出问题了,请ping我


2

在另一个问题中提出了一个答案,但是已经关闭,我也希望社区也能尝试一下。

boolean gpsStatus = locmanager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsStatus) {
    Settings.Secure.putString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "network,gps");
}

看到 此评论

此解决方案需要WRITE_SETTINGSWRITE_SECURE_SETTINGS权限。


@milind,假设我有一个植根设备,我应该怎么做才能使用此代码?我尝试获得该应用程序的root权限,但是并没有帮助。它一直说:“拒绝权限:写入安全设置需要android.permission.WRITE_SECURE_SETTINGS”
android开发者

@android阅读这篇文章的最后一句话。使用此方法将需要android.permission.WRITE_SECURE_SETTINGS清单中的许可。
gobernador 2012年

1
我知道 。我已经添加了它。它告诉我,即使它已经在清单中了。
Android开发人员


所以即使是植根设备也不可能吗?
Android开发人员

2

也许在课堂上有反思的技巧android.server.LocationManagerService

此外,还有一种方法(自API 8起) android.provider.Settings.Secure.setLocationProviderEnabled


3
此类Settings.Secure似乎很有希望,但是我收到一个安全异常,说我需要android.permission.WRITE_SECURE_SETTINGS,即使将这个权限(也包括WRITE_SETTINGS)添加到清单中,我仍然会收到错误消息。但这似乎是继续搜索的好方法。谢谢:)
maid450

WRITE_SECURE_SETTINGS有一个保护级别,systemOrSignature您需要将该应用程序设为系统应用程序才能正常工作,此答案中也提到了这一点
流动

2

这是所提供的最佳解决方案Google Developers。初始化后,只需在onCreate的onResume中调用此方法GoogleApiClient

private void updateMarkers() {
    if (mMap == null) {
        return;
    }

    if (mLocationPermissionGranted) {
        // Get the businesses and other points of interest located
        // nearest to the device's current location.
         mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API).build();
        mGoogleApiClient.connect();
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(10000 / 2);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);


        LocationSettingsRequest.Builder builder = new LocationSettingsRequest
                .Builder()
                .addLocationRequest(mLocationRequest);
        PendingResult<LocationSettingsResult> resultPendingResult = LocationServices
                .SettingsApi
                .checkLocationSettings(mGoogleApiClient, builder.build());

        resultPendingResult.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();
                final LocationSettingsStates locationSettingsStates = locationSettingsResult.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 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(
                                    MainActivity.this,
                                    PERMISSIONS_REQUEST_ACCESS_FINE_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;
                }

            }
        });


        @SuppressWarnings("MissingPermission")
        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    // Add a marker for each place near the device's current location, with an
                    // info window showing place information.
                    String attributions = (String) placeLikelihood.getPlace().getAttributions();
                    String snippet = (String) placeLikelihood.getPlace().getAddress();
                    if (attributions != null) {
                        snippet = snippet + "\n" + attributions;
                    }

                    mMap.addMarker(new MarkerOptions()
                            .position(placeLikelihood.getPlace().getLatLng())
                            .title((String) placeLikelihood.getPlace().getName())
                            .snippet(snippet));
                }
                // Release the place likelihood buffer.
                likelyPlaces.release();
            }
        });
    } else {
        mMap.addMarker(new MarkerOptions()
                .position(mDefaultLocation)
                .title(getString(R.string.default_info_title))
                .snippet(getString(R.string.default_info_snippet)));
    }
}

注意:这行代码会自动打开对话框(如果Location未打开)。这条线也用在Google Map中

 status.startResolutionForResult(
 MainActivity.this,
 PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

什么是mLocationPermissionGranted
b devloper

用于检查是否授予“位置”权限。这是run time授予的权限。
阿曼·辛格

您还可以通过简单地将值设置为true来进行操作(如果您已经获得了棒棒糖前置设备的许可)
AMAN SINGH,2017年

2

此代码适用于ROOTED手机:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] cmds = {"cd /system/bin" ,"settings put secure location_providers_allowed +gps"};
        try {
            Process p = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            for (String tmpCmd : cmds) {
                os.writeBytes(tmpCmd + "\n");
            }
            os.writeBytes("exit\n");
            os.flush();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

要关闭GPS,您可以改用此命令

settings put secure location_providers_allowed -gps

您还可以使用以下命令切换网络准确性:开启使用:

settings put secure location_providers_allowed +network

对于关闭,您可以使用:

settings put secure location_providers_allowed -network

1

自发布此问题以来,情况已经发生变化,现在有了新的Google Services API,您可以提示用户启用GPS:

https://developers.google.com/places/android-api/current-place

您需要在清单中请求ACCESS_FINE_LOCATION权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

另请观看此视频:

https://www.youtube.com/watch?v=F0Kh_RnSM0w


谢谢。但是Google Play Services 7可以与旧的android版本一起使用吗?(API
14-23

1

这对我有用。

比Rj0078在此问题中的答案(https://stackoverflow.com/a/42556648/11211963)更简单,但该方法也能正常工作。

它显示如下对话框:

在此处输入图片说明

(写在科特林)

    googleApiClient = GoogleApiClient.Builder(context!!)
        .addApi(LocationServices.API).build()
    googleApiClient!!.connect()
    locationRequest = LocationRequest.create()
    locationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    locationRequest!!.interval = 30 * 1000.toLong()
    locationRequest!!.fastestInterval = 5 * 1000.toLong()

    val builder = LocationSettingsRequest.Builder()
        .addLocationRequest(locationRequest!!)
    builder.setAlwaysShow(true)

    result =
       LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build())
    result!!.setResultCallback { result ->
        val status: Status = result.status
        when (status.statusCode) {
            LocationSettingsStatusCodes.SUCCESS -> {
               // Do something
            }
            LocationSettingsStatusCodes.RESOLUTION_REQUIRED ->
                try {
                    startResolutionForResult(),
                    status.startResolutionForResult(
                        activity,
                        REQUEST_LOCATION
                    )
                } catch (e: SendIntentException) {
                }
            LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                // Do something
            }
        }
    }

0

你只需要删除LocationListenerLocationManager

manager.removeUpdates(listener);

-1

使用此代码简单易用:

权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

请遵循以下代码以编程方式访问GPS:

LocationManager locationManager ;
 boolean GpsStatus ;


            GPSStatus();

            if(GpsStatus == true)
            {
                textview.setText("Your Location Services Is Enabled");
            }else
                {textview.setText("Your Location Services Is Disabled");}

            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);


    public void GPSStatus(){
    locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
    GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.