为什么this标红 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { return; }
时间: 2024-02-14 13:07:25 浏览: 31
`this` 标红的原因是因为上下文(Context)对象不能直接在非 Activity 或 Fragment 的类中使用。解决这个问题的方法是将上下文对象传递给该类或使用适当的上下文。
在你提供的代码中,`this` 可能是在一个非 Activity 或 Fragment 的类中使用,因此它标红了。你可以将上下文对象传递给该类,或者使用适当的上下文对象,例如:
```java
public class MyBluetoothClass {
private Context context;
public MyBluetoothClass(Context context) {
this.context = context;
}
public void checkBluetoothPermission() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
// Bluetooth permission has already been granted, do the task.
}
}
```
在上面的代码中,我们将上下文对象保存在 `context` 变量中,并在 `checkBluetoothPermission()` 方法中使用它来检查 `BLUETOOTH_CONNECT` 权限。这样,就不需要在非 Activity 或 Fragment 类中使用 `this` 了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)