欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

网上打开与关闭gps几种方案测试,其中方案3可行

程序员文章站 2022-03-12 19:29:29
对于网上提到的几种开启或者关闭GPS方案,分别进行了测试,开发环境android 7.0,时间202007;其中方案1和2,成功;方案3,成功;方案1:(失败) // 这段代码可以实现GPS开关状态的切换-经过测试不行;20200722// Intent GPSIntent = new Intent();// GPSIntent.setClassName("com.android.settings",// "c......

       对于网上提到的几种开启或者关闭GPS方案,分别进行了测试,开发环境android 7.0,时间202007;

其中方案1和2,成功;方案3,成功;

方案1:(失败)

    // 这段代码可以实现GPS开关状态的切换-经过测试不行;20200722
//        Intent GPSIntent = new Intent();
//        GPSIntent.setClassName("com.android.settings",
//                "com.android.settings.widget.SettingsAppWidgetProvider");
//        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
//        GPSIntent.setData(Uri.parse("custom:3"));
//        try {
//            PendingIntent.getBroadcast(MainActivity.this, 0, GPSIntent, 0).send();
//        } catch (PendingIntent.CanceledException e) {
//            e.printStackTrace();
//        }
//        try {
//            Thread.sleep(2000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

方案2:(失败)

Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);

在权限添加这里卡住,提示需要在系统-app目录下;

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

方案3:(可以)

 

//开启GPS
public static final String GPS_ON = "settings put secure location_providers_allowed +gps";
    
//关闭GPS
public static final String GPS_OFF = "settings put secure location_providers_allowed -gps";
 
//查看GPS状态
public static final String QUERY_GPS_STATE = "settings get secure location_providers_allowed";
 

参考:https://blog.csdn.net/u013512708/article/details/103087761?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-6 

private void toggleGPS(String cmd){
    //Runtime对象
    Runtime runtime = Runtime.getRuntime();
    OutputStream localOutputStream=null;
    DataOutputStream localDataOutputStream=null;

    try {
        Process localProcess = runtime.exec("su");
        localOutputStream = localProcess.getOutputStream();
        localDataOutputStream = new DataOutputStream(localOutputStream);
        localDataOutputStream.writeBytes(cmd);
        localDataOutputStream.flush();
        Log.e(TAG,"执行命令"+cmd);
    } catch (IOException e) {
        //MyLog.e(TAG+"strLine:"+e.getMessage());
        e.printStackTrace();
    }finally {
        if(localDataOutputStream!= null){
            try {
                localDataOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(localOutputStream!= null){
            try {
                localOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

本文地址:https://blog.csdn.net/qq81260290/article/details/107514412

相关标签: android JAVA