我正在尝试捕获蓝牙设备断开意图过滤器。我在Onceeive中添加了一个日志,但它永远不会达到它,也没有在logcat中显示。我怀疑问题是我的清单。xml配置:
清单:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="com.company.MyReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
<action android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED" />
</intent-filter>
</receiver>
<activity
android:name=".BTActivity"
android:label="BTActivity" >
</activity>
</application>
</manifest>
myreceiver扩展了广播员:
@Override
public void onReceive(Context context, Intent intent) {
Log.i("got-in", "got-in-");
// String action = intent.getAction();
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("disconnect", device.getName());
Intent i = new Intent(context, BTActivity.class);
Bundle b = new Bundle();
b.putString("deviceName", device.getName());
intent.putExtras(b); // Put your id to your next Intent
context.startActivity(i);
// finish();
}
使用此代码接收断开连接(蓝牙仍打开时):
<intent-filter> <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
您还必须注册一项服务,然后注册一个广播接收器以进行蓝牙状态更改,因此您的应用知道何时关闭蓝牙,因此丢弃了所有活动设备,因为您将不会在何时仅转动蓝牙时收到ACL_Disconnect关闭。
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(bluetoothTurnedOnOff, filter);
return START_STICKY;
}
private final BroadcastReceiver bluetoothTurnedOnOff = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
[...]
适用于新用户。它将有效。您的清单文件外观
<receiver android:name="(package name).BluetoothReceiver" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
</receiver>
,您的接收器看起来像
else if (intent.getAction().equals(`enter code here`
BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
// connection lost
尝试从Intent-Filter中删除<category .../>
,然后重试。
尝试android.bluetooth.device.action.acl_discontected在Intent Filter中的操作。它应该解决您的问题。