2012-11-10 26 views
0

我有行動中的BroadcastReceiver服務。該服務在啓動時啓動並繼續運行,並且我有一項活動可以讓我檢查服務正在運行並啓動/停止服務。從藍牙設備連接/斷開連接時,我沒有收到任何意圖。我正在運行Android 2.3的HTC Desire S上測試此功能。我試圖在清單中註冊BroadcastReceiver,但無濟於事。BroadcastReceiver ACTION_ACL_CONNECTED從未收到

下面是代碼:

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" /> 
+0

你有t他藍牙權限設置? – NikkyD

+1

我忘記了藍牙許可。我現在工作正常。謝謝 ! – Shessel

回答

2

按用戶評論,他錯過了加入藍牙權限

<uses-permission android:name="android.permission.BLUETOOTH" /> 
相關問題