Android 如何启用定位?

Android 如何启用定位?,android,location,Android,Location,您好,在下面的代码中,我正在通过蓝牙和位置连接设备。 这是它第一次请求允许打开该位置,但它没有启用该位置 protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_device); ButterKnife.bind(this);

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

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();
            }
        }
    }
有谁能帮助我如何像下面代码中的buetooth一样自动启用位置

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

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();
            }
        }
    }
protectedvoid onCreate(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u scan\u设备);
把(这个)绑起来;
mProgressDialog=新建进度对话框(此);
mPref=PreferenceManager.getDefaultSharedReferences(getApplicationContext());
initToolBar();
mBleDevices=newarraylist();
mAdapter=新设备适配器(本);
mDeviceListView.setAdapter(mAdapter);
LinearLayoutManager=newlinearlayoutmanager(this,LinearLayoutManager.VERTICAL,false);
mDeviceListView.setLayoutManager(管理器);
mDeviceListView.addOnItemTouchListener(新的RecyclerItemClickListener(这个,新的RecyclerItemClickListener.OnItemClickListener(){
@凌驾
公共虚线单击(视图,int位置){
showProgressDialog();
列出bluetoothDevices=mAdapter.getBluetoothDevices();
if(蓝牙设备!=null){
if(bluetoothDevices.size()>位置){
BluetoothDevice BluetoothDevice=bluetoothDevices.get(位置);
if(蓝牙设备!=null){
字符串地址=bluetoothDevice.getAddress();
连接(地址);
}
}
}
}
}));
final IntentFilter IntentFilter=新IntentFilter();
intentFilter.addAction(找到BleService.ACTION\u设备);
intentFilter.addAction(BleService.ACTION\u GATT\u已连接);
intentFilter.addAction(BleService.ACTION\u GAT\u连接);
intentFilter.addAction(BleService.ACTION\u GATT\u断开连接);
intentFilter.addAction(BleService.ACTION\u GAT\u SERVICE\u DISCOVERED);
registerReceiver(mGattUpdateReceiver、intentFilter);
if(ContextCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.ACCESS\u位置)!=PackageManager.permission\u已授予){
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.O){
requestPermissions(新字符串[]{Manifest.permission.ACCESS_粗略_位置,Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_精细_位置
,Manifest.permission.BLUETOOTH\u ADMIN,Manifest.permission.ACCESS\u FINE\u LOCATION},permission\u REQUEST\u rough\u LOCATION);
}
}否则{
if(mServiceConnection!=null){
Intent enablebintent=新意图(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(enableBtIntent,101);
}
Intent Intent=新Intent(这个,BleService.class);
bindService(intent、mServiceConnection、Context.BIND\u AUTO\u CREATE);
}
}
私有void showProgressDialog(){
如果(mProgressDialog==null){
mProgressDialog=新建进度对话框(此);
}
setMessage(getString(R.string.load));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
专用ServiceConnection mServiceConnection=新ServiceConnection(){
@凌驾
服务连接上的公共无效(ComponentName ComponentName,IBinder IBinder){
mBleService=((BleService.LocalBinder)iBinder.getLeService();
if(服务!=null){
mBleService.scanlevice(true);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(R.string.scanning_设备);
}
}
@凌驾
ServiceDisconnected上的公共无效(ComponentName ComponentName){
}
};
@凌驾
受保护的void onResume(){
super.onResume();
}
@凌驾
受保护的void onStart(){
super.onStart();
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
if(requestCode==101){
if(服务!=null){
mBleService.scanlevice(true);
}
}
}
private BroadcastReceiver mGattUpdateReceiver=新的BroadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
String action=intent.getAction();
开关(动作){
案例BleService.ACTION\u设备\u找到:
BluetoothDevice设备=(BluetoothDevice)intent.getParcelableExtra(BleService.EXTRA_设备);
如果(设备!=null){
如果(!mBleDevices.contains(设备)){
添加(设备);
mAdapter.蓝牙设备(蓝牙设备);
mAdapter.notifyDataSetChanged();
}
}
打破
案例BleService.ACTION\u GATT\u连接:
Log.d(标记“!Action gat connected…”);
mBleService.scanlevice(假);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connected));
打破
案例BleService.ACTION\u GAT\u连接:
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connecting));
Log.d(标记“!Actio