Programmatically register a broadcast receiver

后端 未结 10 1633
[愿得一人]
[愿得一人] 2020-11-22 05:00

I\'d like to know what is the best practice/way of programmatically register a broadcast receiver. I want to register specific receivers according to user choice.

As

相关标签:
10条回答
  • 2020-11-22 05:26

    One important point that people forget to mention is the life time of the Broadcast Receiver. The difference of programmatically registering it from registering in AndroidManifest.xml is that. In the manifest file, it doesn't depend on application life time. While when programmatically registering it it does depend on the application life time. This means that if you register in AndroidManifest.xml, you can catch the broadcasted intents even when your application is not running.

    Edit: The mentioned note is no longer true as of Android 3.1, the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage → Application). https://developer.android.com/about/versions/android-3.1.html

    This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents.

    So it can be understood as receivers programmatically registered in Application's onCreate() would have same effect with ones declared in AndroidManifest.xml from Android 3.1 above.

    0 讨论(0)
  • 2020-11-22 05:26
    package com.example.broadcastreceiver;
    
    
    import android.app.Activity;
    import android.content.IntentFilter;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
       UserDefinedBroadcastReceiver broadCastReceiver = new UserDefinedBroadcastReceiver();
    
       @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
       }
    
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
       }
    
       /**
        * This method enables the Broadcast receiver for
        * "android.intent.action.TIME_TICK" intent. This intent get
        * broadcasted every minute.
        *
        * @param view
        */
       public void registerBroadcastReceiver(View view) {
    
          this.registerReceiver(broadCastReceiver, new IntentFilter(
                "android.intent.action.TIME_TICK"));
          Toast.makeText(this, "Registered broadcast receiver", Toast.LENGTH_SHORT)
                .show();
       }
    
       /**
        * This method disables the Broadcast receiver
        *
        * @param view
        */
       public void unregisterBroadcastReceiver(View view) {
    
          this.unregisterReceiver(broadCastReceiver);
    
          Toast.makeText(this, "unregistered broadcst receiver", Toast.LENGTH_SHORT)
                .show();
       }
    }
    
    0 讨论(0)
  • 2020-11-22 05:27

    According to Listening For and Broadcasting Global Messages, and Setting Alarms in Common Tasks and How to Do Them in Android:

    If the receiving class is not registered using in its manifest, you can dynamically instantiate and register a receiver by calling Context.registerReceiver().

    Take a look at registerReceiver (BroadcastReceiver receiver, IntentFilter filter) for more info.

    0 讨论(0)
  • 2020-11-22 05:30

    Two choices

    1) If you want to read Broadcast only when the Activity is visible then,

    registerReceiver(...) in onStart() and unregisterReceiver(...) in onStop()

    2) If you want to read Broadcast even if Activity is in Background then,

    registerReceiver(...) in onCreate(...) and unregisterReceiver(...) in onDestroy()

    Bonus:

    If you are lazy

    If you don't want to write boilerplate code for registering and unregistering a BroadcastReceiver again and again in each Activity then,

    1. Create an abstract Activity
    2. Write boilerplate code in Activity
    3. Leave the implementation as abstract methods

    Here is the code snippet:

    Abstract Activity

    public abstract class BasicActivity extends AppCompatActivity {
    
        private BroadcastReceiver broadcastReceiver;
        private IntentFilter filter;
        private static final String TAG = "BasicActivity";
    
        /**********************************************************************
        *                   Boilerplate code
        **********************************************************************/
    
        @Override
        public void onCreate(Bundle sis){
            super.onCreate(sis);
            broadcastReceiver = getBroadcastReceiver();
            filter = getFilter();
        }
    
        @Override
        public void onStart(){
            super.onStart();
            register();
        }
    
        @Override
        public void onStop(){
            super.onStop();
            unregister();
        }
    
        private void register(){
            registerReceiver(broadcastReceiver,filter);
        }
    
        private void unregister(){
            unregisterReceiver(broadcastReceiver);
        }
    
        /**********************************************************************
        *                   Abstract methods
        **********************************************************************/
    
        public abstract BroadcastReceiver getBroadcastReceiver();
    
        public abstract IntentFilter getFilter();
    
    }
    

    Using this approach you can write more boilerplate code such as writing common animations, binding to a service, etc.

    See full code:

    HERE

    0 讨论(0)
提交回复
热议问题