我正在尝试收听蓝牙连接/断开事件,以确定是否连接了蓝牙设备。我试图这样做,以便我的应用程序将在较旧的Android版本上运行。
我在清单中注册了接收器:
<receiver
android:name=".BluetoothReceiver">
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
</intent-filter>
</receiver>
在我的BluetoothReceiver课程中,我有
public class BluetoothReceiver extends BroadcastReceiver{
public final static String TAG = "BluetoothReciever";
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "Bluetooth Intent Recieved");
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equalsIgnoreCase(action))
{
Log.d(TAG, "Connected to " + device.getName());
}
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equalsIgnoreCase(action))
{
Log.d(TAG, "Disconnected from " + device.getName());
}
}}
但是当连接和断开蓝牙时,没有任何反应。我做错了什么?
答案 0 :(得分:0)
如果连接了蓝牙耳机,您必须操纵MODIFY_AUDIO_SETTINGS
以正确指责。一旦您正确定义了您的意图,并正确配置了清单,它就应该有效。这适用于耳机插孔,但如果您使用上述内容,则可以应用于蓝牙。
以下是两个可能有助于更详细解释的网站:
你必须定义你的意图;否则它将无法访问系统功能。广播接收器;将提醒您的应用程序您想要收听的更改。
每个接收器都需要进行子类化;它必须包含onReceive()
。要实现onReceive()
,您需要创建一个包含两个项目的方法:Context&amp;意图。
更有可能服务是理想的;但是你将创建一个服务并通过它定义你的上下文。在上下文中;你会定义你的意图。
一个例子:
context.startService
(new Intent(context, YourService.class));
非常基本的例子。然而;您的特定目标是利用系统范围的广播。您希望通知您的应用程序Intent.ACTION_HEADSET_PLUG
。
如何通过清单订阅:
<receiver
android:name="AudioJackReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
或者您可以通过您的应用程序进行简单定义;但。你的特殊要求;如果您想要检测Bluetooth MODIFY_AUDIO_SETTINGS
,则需要用户权限。
<强>更新强>
我误解了你的问题,我以为你在试图寻找蓝牙耳机;不只是任何蓝牙Paired
。
结束question;他们解释了如何检查Paired Bluetooth Devices
。
导入蓝牙套餐。
import android.bluetooth.*;
设置权限。
<uses-permission android:name="android.permission.BLUETOOTH" />
访问蓝牙适配器:
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
运行检查连接不是null
。
if(bluetooth!= null) { // 做一点事。 }
确保已启用:
if (bluetooth.isEnabled())
{
// Enabled, do some work with Bluetooth
}
else
{
// Not Enabled Do something else.
}
显示蓝牙状态BluetoothAdapter.getState()
默认情况下,它已关闭;所以你必须启用它。
string state = bluetooth.getState();
status = deviceName + " : " + deviceLocation + " : " + deviceState;