2016-01-26 8 views
1

Я пытаюсь реализовать Bluetooth Discovery в 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 для этой цели. Для того, чтобы позвонить registerReceiver, вам нужен действительный начальный объект Context. Избавьтесь от 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){ 

     } 

    } 
}; 

} 
Смежные вопросы