我正試圖在Android中實現藍牙發現。我想把這個動作放在與我的應用程序的MainActivity不同的類中。我試圖用AppCompatActivity擴展我的新類,但它不起作用。我無法註冊接收器。這是代碼的一小部分。在類中註冊BroadcastReceiver
public class BTManager extends AppCompatActivity {
public void scanDevices()
{
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter1);
registerReceiver(mReceiver, filter2);
myBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
DiscoveredDeviceList.add(device);
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
}
catch(Exception e)
{
}
}
};
}
*,但它不工作*。怎麼了 ? – Blackbelt
執行registerReceiver(mReceiver,filter1)時,應用程序崩潰; – Daniele
它如何崩潰?使用此代碼 – Blackbelt