移动数据和GPS可编程开/关-Android 5.0以上版本

移动数据和GPS可编程开/关-Android 5.0以上版本,android,gps,3g,4g,Android,Gps,3g,4g,我想实现启用/禁用移动数据和GPS设置。 我已经搜索了可用的启用/禁用移动数据和GPS设置的Android API,下面是我的发现 启用/禁用移动数据- 1.可以在中执行启用/禁用。我们正在更改GPS设置,而无需使用设置SAPI移动到设置屏幕 要检查GPS是否打开或关闭,您必须按如下方式进行检查 public class GPSActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.C

我想实现
启用/禁用移动数据和GPS设置
。 我已经搜索了可用的启用/禁用移动数据和GPS设置的Android API,下面是我的发现

启用/禁用移动数据-
1.可以在中执行启用/禁用。我们正在更改GPS设置,而无需使用设置SAPI移动到设置屏幕

要检查GPS是否打开或关闭,您必须按如下方式进行检查

public class GPSActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private static String TAG = "GPSActivity";

// Required for setting API
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
GoogleApiClient googleApiClient;

private Button mBtnGPS;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gps);

    mBtnGPS = (Button) findViewById(R.id.btnGPS);

    mBtnGPS.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btnGPS:
            // Check GPS
            checkGps();
            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);
    if (requestCode == REQUEST_CHECK_SETTINGS) {
        googleApiClient = null;
        checkGps();
    }
}

public void checkGps() {
    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient.Builder(GPSActivity.this)
                .addApiIfAvailable(LocationServices.API)
                .addConnectionCallbacks(this).addOnConnectionFailedListener(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:
                        Log.i("GPS", "SUCCESS");
                        //getFbLogin();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.i("GPS", "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(GPSActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.i("GPS", "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;
                    case LocationSettingsStatusCodes.CANCELED:
                        Log.i("GPS", "CANCELED");
                        break;
                }
            }
        });
    }
}

@Override
public void onConnected(Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
公共类GPSActivity扩展了AppCompativity实现了View.OnClickListener、GoogleAppClient.ConnectionCallbacks、GoogleAppClient.OnConnectionFailedListener{
私有静态字符串TAG=“GPSActivity”;
//需要设置API
受保护的静态最终整数请求检查设置=0x1;
GoogleapClient GoogleapClient;
专用按钮mBtnGPS;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
mBtnGPS=(按钮)findviewbyd(R.id.btnGPS);
mBtnGPS.setOnClickListener(此);
}
@凌驾
公共void onClick(视图){
开关(view.getId()){
案例R.id.btnGPS:
//检查全球定位系统
检查GPS();
打破
}
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
Log.d(标记“onActivityResult”(“+requestCode+”,“+resultCode+”,“+data”);
if(requestCode==请求检查设置){
GoogleAppClient=null;
检查GPS();
}
}
公共无效检查GPS(){
if(googleApiClient==null){
GoogleAppClient=新的GoogleAppClient.Builder(GPSActivity.this)
.addapiAvailable(LocationServices.API)
.addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
googleApiClient.connect();
LocationRequest LocationRequest=LocationRequest.create();
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
位置请求设置间隔(30*1000);
locationRequest.SetFastTestInterval(5*1000);
LocationSettingsRequest.Builder=新建LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);//这是关键要素
Pendingreult结果=LocationServices.SettingsApi
.checkLocationSettings(GoogleAppClient,builder.build());
result.setResultCallback(新的ResultCallback(){
@凌驾
公共void onResult(位置设置结果){
最终状态状态=result.getStatus();
最终位置设置状态状态=结果
.getLocationSettingsStates();
开关(status.getStatusCode()){
案例位置设置StatusCodes.SUCCESS:
Log.i(“GPS”、“成功”);
//getFbLogin();
打破
案例位置设置StatusCodes.RESOLUTION_要求:
日志i(“GPS”,“需要分辨率”);
//不满足位置设置。但可能是
//通过显示用户来修复
//对话。
试一试{
//通过调用显示对话框
//StartResult()的解决方案,
//并在onActivityResult()中检查结果。
status.startResolutionForResult(GPSActivity.this,请求检查设置);
}catch(IntentSender.sendtintentexe){
//忽略错误。
}
打破
案例位置设置StatusCodes.SETTINGS\u CHANGE\u不可用:
Log.i(“GPS”,“设置更改”不可用);
//位置设置不满意。但是,我们有
//没有办法解决这个问题
//设置,这样我们就不会显示对话框。
打破
案例位置设置StatusCodes.Cancelled:
Log.i(“GPS”、“取消”);
打破
}
}
});
}
}
@凌驾
未连接的公共空间(捆绑包){
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
}
}


这是如何启动GPS和网络(Wi-Fi/数据)提供商提供的定位服务

LocationManager locationManager = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);        
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
如果要停止侦听位置更新,请运行以下代码:
locationManager.removeUpdates(locationListener);

这一行代码将停止侦听任何位置更新,而不考虑提供商(GPS/网络),因为LocationManager不关心更新来自何处

在您的情况下,我假设您知道如何创建一些UI,让用户决定是否使用GPS/网络。然后,您可以执行以下操作:

if ( useGPS ) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
if ( useNetwork ) {
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
}
如果用户同时启用了这两个提供程序,则位置更新可能会更准确。如果用户同时禁用了这两个提供程序,则无所谓。因为LocationListener不会有任何更新,这应该是用户想要的

顺便说一下,下面是创建LocationListener的代码:

LocationListener locationListener =  new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // you may add some logic here to determine whether the new location update is more accurate than the previous one
            if ( isBetterLocation(location,currentBestLocation) ) {
                currentBestLocation = location;
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };

调用RemovelocationUpdate()停止使用GPS。您是否向应用程序中的用户请求运行时权限?@arpittatel我正在寻找一种方法来执行此操作,但要从应用程序中执行。是否有任何可能/可用的解决方案?否…因为此控件可能仍由用户使用。开发人员通常需要权限才能使GPS使用它,disabling GPS不是不需要使用它的东西:)我使用了相同的代码来启用它。