Broadcast Receiver class and registerReceiver method

前端 未结 3 842
春和景丽
春和景丽 2020-11-30 05:53

Hi i am trying to understand Broadcast Receiver , i went through many sample codes , but still have some doubts. I wanted to know when we have to extend the Broadcast Receiv

3条回答
  •  星月不相逢
    2020-11-30 06:51

    Android has intent action for broadcast receiver. BroadCast receiver will be trigger when it listen any action which registered within it.

    Now we will take one example : That we need to listen the action of "whenever any bluetooth device connect to our device". For that android has it fix action android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED

    So you can get it via manifest & registration also

    BY Manifest Registration:

    Put this in your manifest

    
        
                    
          
    
    

    Create MyBTReceiver.class

    public class MyBTReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            if(intent.getAction().equals("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")){
                Log.d(TAG,"Bluetooth connect");
            }
        }
    }
    

    That was the simplest broadcast Receiver.

    Now, if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). You can also register it within your existing class file. you also need to unregister it onDestroy(). here, you dont need any broadcast registration in manifest except activity registration

    For example

    public class MainActivity extends Activity {
    
        IntentFilter filter1;
    
        @Override
        public void onCreate() {
            filter1 = new IntentFilter("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED");
            registerReceiver(myReceiver, filter1);
        }
    
        //The BroadcastReceiver that listens for bluetooth broadcasts
        private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction().equalsIgnoreCase("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")) {
                    Log.d(TAG,"Bluetooth connect");
                }
            }
        };
    
        @Override
        public void onDestroy() {
            unregisterReceiver(myReceiver);
        }
    }
    

提交回复
热议问题