0

我有一个BroadcastReceiver关于ACTION_ACL_CONNECTED行动的服务。该服务在启动时启动并继续运行,我有一个活动允许我检查服务是否正在运行并启动/停止它。连接/断开蓝牙设备时,我没有收到任何意图。我正在运行 Android 2.3 的 HTC Desire S 上对此进行测试。我试图BroadcastReceiver在清单中注册,但无济于事。

这是代码:

public class BTDetectSrv  extends Service {
public IBinder onBind(Intent intent)
{
    return null;
}

@Override
public void onCreate() 
{               
    Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    IntentFilter filter1, filter2, filter3, filter4;
    filter1 = new IntentFilter("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
    filter2 = new IntentFilter(android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED);
    filter3 = new IntentFilter(android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED);
    filter4 = new IntentFilter(android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    this.registerReceiver(mReceiver, filter1);
    this.registerReceiver(mReceiver, filter2);
    this.registerReceiver(mReceiver, filter3);
    this.registerReceiver(mReceiver, filter4);
    return START_STICKY;
}

//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        Toast.makeText(BlueDetectSrv.this, "BT change received !", Toast.LENGTH_LONG).show();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            Toast.makeText(BlueDetectSrv.this, device.getName() + " Device found", Toast.LENGTH_LONG).show();
        }
        else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            Toast.makeText(BlueDetectSrv.this, device.getName() + " Device is now connected", Toast.LENGTH_LONG).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
            Toast.makeText(BlueDetectSrv.this, device.getName() + " Device is about to disconnect", Toast.LENGTH_LONG).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Toast.makeText(BlueDetectSrv.this, device.getName() + " Device has disconnected", Toast.LENGTH_LONG).show();
        }           
    }
};

@Override
public void onDestroy() 
{
    this.unregisterReceiver(mReceiver);
    Toast.makeText(this, "BlueDetect Stopped", Toast.LENGTH_LONG).show();
}

}

我在清单中添加了以下权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
4

1 回答 1

2

根据用户评论,他错过了添加蓝牙权限

<uses-permission android:name="android.permission.BLUETOOTH" />
于 2015-04-06T10:54:29.943 回答