2016-01-26 84 views
1

我正試圖在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) 
      { 

      } 

    } 
    }; 
} 
+0

*,但它不工作*。怎麼了 ? – Blackbelt

+0

執行registerReceiver(mReceiver,filter1)時,應用程序崩潰; – Daniele

+0

它如何崩潰?使用此代碼 – Blackbelt

回答

0

呼叫scanDevices()在:public BTManager() { Initialize_Bluetooth(); scanDevices(); }

你不能使用默認Constructor用於這一目的。你需要一個有效的初始化Context對象來呼叫registerReceiver。擺脫public BTManager()和移動

Initialize_Bluetooth(); 
scanDevices(); 

onCreate

+0

我如何可以從在MainActivity調用類? – Daniele

+0

在MainActivity中移動該代碼是最簡單的方法 – Blackbelt

+0

如果我需要將此代碼放在不同的類中,我該怎麼做? – Daniele

0
public class BTManager extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
///// your code 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    IntentFilter intentFilter = new IntentFilter(); 
    intentFilter.addAction(BluetoothDevice.ACTION_FOUND); 
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
    registerReceiver(broadcastReceiver, intentFilter); 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    unregisterReceiver(broadcastReceiver); 
} 

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){ 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     try { 
     String action = intent.getAction(); 
     if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
    BluetoothDevice device =  intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
      String deviceName = device.getName(); 
      DiscoveredDeviceList.add(device); 
     } 
     if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){ 

     } 
    }catch(Exception e){ 

     } 

    } 
}; 

} 
相關問題