как включить в локацию? - PullRequest
0 голосов
/ 10 апреля 2019

Привет в коде ниже, я подключаю устройства через Bluetooth и местоположение. Впервые он запрашивает разрешение на включение местоположения, но не разрешает местоположение.

Может кто-нибудь, пожалуйста, помогите мне, как автоматически включить местоположение как buetooth в коде ниже

Например: в bluetooth запрашивает разрешение и включает его. но для местоположения в первый раз он запрашивает разрешение, но не разрешает местоположение.

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 голосов
/ 10 апреля 2019

Вы не можете включить местоположение программно, если устройство не имеет рута.

Вот код, как попросить пользователя включить местоположение во фрагменте:

 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()
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...