首页 > 解决方案 > hasSystemFeature 没有返回任何东西

问题描述

我有一个奇怪的问题。我正在一个 android 应用程序中实现蓝牙连接。在清单中,我有权:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

我在活动中也有这些意图:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
    <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
    <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />

    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

由于我在后台使用蓝牙进程的服务和接收器,因此我也对该服务具有以下权限:

        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
        <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
        <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
        <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />

现在,在服务内部,我正在调用以下代码:

if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
   //it is true. bla bla bla
}else{
   //it is false. bla bla bla
}

好吧,我不明白为什么,如果我进入调试模式,getPackageManager 不会返回任何东西。如果我在 if 中放入带有这一行的布尔变量,我可以清楚地看到没有返回任何内容。事实上,这就像代码在那一刻被杀死,因为代码中的任何其他行都被访问了,但我仍然可以操作应用程序。是不是因为错误而被杀死的是服务而不是应用程序本身?我该如何调试呢?因为我看不到任何错误行。知道错误来自哪里吗?

编辑:我在 Android 8.0 上运行它

标签: androidservicebluetooth

解决方案


额外的东西:该函数是在我从服务调用的对象的构造函数中调用的。您需要将上下文传递给对象:

your_object = new your_object( getApplicationContext() );

在对象构造函数内部:

public class your_object{

 public your_object(Context context){
     context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
}

推荐阅读