如何启用定位?

时间:2019-04-10 11:18:45

标签: android location

嗨,在下面的代码中,我正在通过蓝牙和位置连接设备。 这是第一次请求允许打开该位置,但未启用该位置。

任何人都可以帮助我如何在下面的代码中像蓝牙一样自动启用位置

例如:在蓝牙中,它正在请求许可并将其打开。 但是对于首次定位,它正在寻求许可,但未启用该位置。

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_device);
        ButterKnife.bind(this);
        mProgressDialog = new ProgressDialog(this);
        mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        initToolBar();
        mBleDevices = new ArrayList<>();
        mAdapter = new DeviceListAdapter(this);
        mDeviceListView.setAdapter(mAdapter);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mDeviceListView.setLayoutManager(manager);
        mDeviceListView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                showProgressDialog();
                List<BluetoothDevice> bluetoothDevices = mAdapter.getBluetoothDevices();
                if (bluetoothDevices != null) {
                    if (bluetoothDevices.size() > position) {
                        BluetoothDevice bluetoothDevice = bluetoothDevices.get(position);
                        if (bluetoothDevice != null) {
                            String address = bluetoothDevice.getAddress();
                            mBleService.connect(address);
                        }
                    }
                }
            }
        }));
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleService.ACTION_DEVICE_FOUND);
        intentFilter.addAction(BleService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleService.ACTION_GAT_CONNECTING);
        intentFilter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleService.ACTION_GAT_SERVICE_DISCOVERED);
        registerReceiver(mGattUpdateReceiver, intentFilter);

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_FINE_LOCATION
                        , Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        } else {
            if (mServiceConnection != null) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 101);
            }

            Intent intent = new Intent(this, BleService.class);
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }
    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
        }
        mProgressDialog.setMessage(getString(R.string.loading));
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
    }
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBleService = ((BleService.LocalBinder) iBinder).getLeService();
            if (mBleService != null) {
                mBleService.scanLeDevice(true);
                mScanStatus.setVisibility(View.VISIBLE);
                mScanStatus.setText(R.string.scanning_device);
            }
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onStart() {
        super.onStart();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101) {
            if (mBleService != null) {
                mBleService.scanLeDevice(true);
            }
        }
    }
    private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case BleService.ACTION_DEVICE_FOUND:
                    BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BleService.EXTRA_DEVICE);
                    if (mBleDevices != null) {
                        if (!mBleDevices.contains(device)) {
                            mBleDevices.add(device);
                            mAdapter.udpateBluetoothDevices(mBleDevices);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case BleService.ACTION_GATT_CONNECTED:
                    Log.d(TAG, "!Action gat connected...");
                    mBleService.scanLeDevice(false);
                    mScanStatus.setVisibility(View.VISIBLE);
                    mScanStatus.setText(getString(R.string.connected));
                    break;
                case BleService.ACTION_GAT_CONNECTING:
                    mScanStatus.setVisibility(View.VISIBLE);
                    mScanStatus.setText(getString(R.string.connecting));
                    Log.d(TAG, "!Action Gat Connecting..");
                    break;
                case BleService.ACTION_GATT_DISCONNECTED:
                    mScanStatus.setVisibility(View.VISIBLE);
                    mScanStatus.setText(getString(R.string.disconnected));
                    mScanningProgress.setVisibility(View.GONE);
                    mRefresh.setVisibility(View.VISIBLE);
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    Log.d(TAG, "!Action Gat Disconnected..");
                    break;
                case BleService.ACTION_GAT_SERVICE_DISCOVERED:
                    boolean isOperator = mPref.getBoolean(Constants.IS_OPERATOR, false);
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    if (isOperator) {
                        Intent homeIntent = new Intent(DeviceScanActivity.this, HomeScreenActivity.class);
                        startActivity(homeIntent);
                        finish();
                    } else {
                        Intent lightControllIntent = new Intent(DeviceScanActivity.this, LightConfigurationActivity.class);
                        startActivity(lightControllIntent);
                        finish();
                    }
                    mScanStatus.setText(getString(R.string.discoveringService));
                    Log.d(TAG, "!Action Gat Discovering..");
                    break;
            }
        }
    };
    private void initToolBar() {
        mRefresh.setVisibility(View.VISIBLE);
    }
    @OnClick(R.id.refresh)
    public void onClick() {
        mScanStatus.setVisibility(View.VISIBLE);
        mRefresh.setVisibility(View.GONE);
        mScanningProgress.setVisibility(View.VISIBLE);
        mBleDevices.clear();
        mAdapter.udpateBluetoothDevices(new ArrayList<BluetoothDevice>());
        mAdapter.notifyDataSetChanged();
    }
    @Override
    protected void onDestroy() {
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
        super.onDestroy();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_COARSE_LOCATION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (mServiceConnection != null) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, 101);
                }
                Intent intent = new Intent(this, BleService.class);
                bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
            } else {
                finish();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

如果设备未植根,则无法通过编程方式启用位置信息。

这是代码,如何要求用户启用Fragment中的位置:

 override fun checkLocationSettings() {
    if (activity != null) {
        locationSettingsTask.addOnFailureListener(activity!!) { exception ->
            if (exception is ResolvableApiException) {
                try {
                    exception.startResolutionForResult(activity,
                            REQUEST_CODE_CHECK_LOCATION_SETTINGS)
                } catch (ignore: Exception) {
                    // Empty
                }
            }
        }
    }
}


 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE_CHECK_LOCATION_SETTINGS) {
        if (resultCode == RESULT_OK) {
            presenter.resolveCurrentLocation()
        }
    }
}