AntiPattern: freezing a UI with Broadcast Receiver

The worst thing that can happen to your app's responsiveness is an "Application Not Responding" (ANR) dialog.

In android guidelines we can read:

In any situation in which your app performs a potentially lengthy operation, you should not perform the work on the UI thread, but instead create a worker thread and do most of the work there. This keeps the UI thread (which drives the user interface event loop) running and prevents the system from concluding that your code has frozen.

It's very important to understand what is Main Thread.

When an Android app is launched, the system creates a thread for the application which is known as the main thread. If you run up any project under the debugger in Eclipse you will see the main thread.

If your app ties up the UI thread for more than 5 seconds or a BroadcastReceiver does not complete within 10 seconds, Android will throw up the Application Not Responding (ANR) dialog which gives the user the opportunity to quit your app.

The best way to figure things out, you experience them.

Here you can find an example OF WHAT NOT TO DO WITH A BROADCAST RECEIVER.

When we register a receiver with registerReceiver (BroadcastReceiver receiver, IntentFilter filter) we must always remember that the BroadcastReceiver will run in the main activity thread.
This means that our activity is blocked until it ends the method OnReceive ()

In our BAD example (intentionally bad) we will register a Broadcast programmatically.
/**
 * This is an example of WHAT NOT TO DO !!
 *
 */
public class FreezingActivity extends SherlockActivity {

 protected FreezingUIReceiver mReceiver = null;

    private static final String TAG = "FreezingActivity";
    protected static final String FREEZYACTION =
          "it.gmariotti.android.examples.antipattern.FREEZING_ACTION";

    @Override
    protected void onPause() {
       super.onPause();
       unregisterReceiver(mReceiver); //take care to unregister
    }

    @Override
    protected void onResume() {
       super.onResume();
       mReceiver = new FreezingUIReceiver();
       registerReceiver(mReceiver, new IntentFilter(FREEZYACTION));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.simple);
       getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

   /**
    * 
    */
    private void newEvent() {
       Toast.makeText(this, getString(R.string.text_newevent), 1000).show();
    }

   /**
    * Launch Intent Broadcast
    */
    private void launchBroadcast() {
       Toast.makeText(this, getString(R.string.text_broadcast), 1000).show();
       Intent i = new Intent(FREEZYACTION);
       sendBroadcast(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       getSupportMenuInflater().inflate(R.menu.freezing_menu, menu);
       return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
          case android.R.id.home:
             NavUtils.navigateUpFromSameTask(this);
             return true;
          case R.id.menu_refresh:
             launchBroadcast();
             return true;
          case R.id.menu_newevent:
             newEvent();
             return true; 
       }
       return super.onOptionsItemSelected(item);
    }
}
Dynamically registered receivers are called on the UI thread. This means that your receivers blocks any UI handling.
In our example we will take "a long running task".
public class FreezingUIReceiver extends BroadcastReceiver {

    private static final String TAG = "FreezyUIReceiver";
    public FreezingUIReceiver() {}
  
    @Override
    public void onReceive(Context context, Intent intent) {

       Log.d(TAG, "onReceive FREEZING RECEIVER");
  
       //This is an example of WHAT NOT TO DO !!
       try{
          Thread.sleep(15000);
       }catch(Exception e){}
  
       Log.d(TAG, "FREEZING RECEIVER END");
    } 
}
Launch app, click refresh button and the freezing up of the UI is gone!

Here we can see where runs our receiver:

...."Application Not Responding" (ANR) dialog...

You should avoid any long tasks in your BroadcastReceiver.
For any longer tasks you should start a service from within your receiver.


You can get code from GitHub:

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice information, this is will helpfull a lot, Thank for sharing, Keep do posting i like to follow this ui online training

    ReplyDelete
  3. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Security Guard License
    Ontario Security License
    Security License Ontario
    Security License

    Thank you..

    ReplyDelete
  4. Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuff like this.
    Live Webcasting
    Webcasting Solution

    ReplyDelete
  5. Excellent blog thanks for sharing the valuable information..it becomes easy to read and easily understand the information.
    Useful article which was very helpful. also interesting and contains good information.
    to know about python training course , use the below link.

    Python Training in chennai

    Python Course in chennai

    ReplyDelete
  6. Very great blog thanks for sharing the valuable information...

    There is no real formula that can tell anyone how the industry is going to innovate and develop in the future, whether this is in telecom, labor or gig economy.

    future of engineering

    ReplyDelete
  7. It's a very easy on the eyes which makes it much more enjoyable for me and my friends to come here and, You make many others topics information interesting and engaging. You give readers a lot to think about and I appreciate that kind of writing. Thank you and Wish you very happy birthday :) best assignment help -
    Assignment Help in Melbourne -
    university assignment help australia

    ReplyDelete
  8. Appreciate the value! Great article content again sharing! Through with this information's, you have given stand out introduction. Very powerful and have true and fresh information. I am satisfied with your thoughts + knowledge. Thanks for the post and effort :) homework help -
    essay writing service -
    homework answers

    ReplyDelete
  9. All your banking hassle, your payments, and receipts are taken care of. It is, in fact, a single-stop solution to all your monetary transactions. One of the two best things about PayPal is its instantaneity. You don’t have to worry about the transaction getting failed, or taking way too much time. Another thing that makes PayPal worthy is its service availability across the world. It follows you wherever you go to make your life easier and quicker. Let’s discuss steps to making an account, and resolutions to PayPal login issues.
    PayPal login |
    www.amazon.com/mytv |
    youtube.com activate |
    Xfinity Login |
    DirecTV login |

    ReplyDelete
  10. Thanks for sharing informative content randomly landed on your blog but when I go through your blog I feel privileged to read your blog.

    An effective
    Ohio CRM software
    helps to turn the potential leads into successful selling opportunities. Once the needs of the customer are understood, sales employees get talking points that address the situation perfectly from the customer’s point of view. Implementing the best CRM software increases the velocity of your sales efforts without human intervention.

    ReplyDelete
  11. It is extremely nice to see the greatest details presented in an easy and understanding manner. Get Digital Marketing Services At Affordable Price At JeewanGarg.Com (SEO Company in Delhi)

    ReplyDelete
  12. Servo Star is a 250 kva servo voltage stabilizer manufacturer in India and makes them distinct models. 250 kva stabilizers are mainly used in domestic as well as commercial or in industry. We at Servo Star offer a cost-effective 250 kva servo stabilizer price across India. Thus, if looking for any 250 kva servo stabilizer look no further than us.

    ReplyDelete
  13. ISC888 สมัคร ฟรี ฝาก-ถอน รวดเร็ว ไม่เกิน 5 นาที เราคือผู้ให้บริการ เว็บไซต์เดิมพันออนไลน์ที่ดีที่สุด ได้รับความนิยมเป็นอย่างมากในประเทศไทย ภายในเว็บไซต์ของเรานั้น มีวิธีเล่น เกมเดิมพันออนไลน์ต่างๆมากมาย

    ReplyDelete
  14. Emedkit India is one of the pioneers and the most reputable company that provides the best breast cancer medicine price in India. One can easily access breast cancer medicines anywhere globally from Emedkit at affordable prices along with blazing speed delivery and free delivery.

    ReplyDelete
  15. Assignment help in Saudi Arabia allows students to finish their papers on time without having any mistakes. If you want to submit error-free papers in your universities, you must think about Online Assignment help in Saudi Arabia.

    ReplyDelete
  16. BHI Makeup Academy is the best Makeup Academy in Mumbai where you learn Makeup & hair styling courses from Industry Experts from Bollywood, Hollywood & International Makeup Industry.

    ReplyDelete
  17. Use Assignment Help services to finish your work effectively. If you are facing issues in writing your academic papers, you must use an online source of expert help. It is quite obvious to pay someone to do my assignment seem difficult to you when you don’t have complete information about the service provider. So, it is good to dig out the full details of your selected service provider and pay the price as soon as possible.

    ReplyDelete

  18. I am always left astounded at the level of dedication and hard work you put in every situation. May you reach every height of success!
    tamilprint 2021
    soap2day 2021
    9xrockers 2021
    klwap2021
    extramovies 2021
    skymovieshd 2021
    300mbmovies 2021
    123movierulz 2021

    ReplyDelete
  19. A sandblaster has become an outstanding tool for smoothing and polishing rough surfaces before its resurfacing or painting. The sandblaster shoots out compelled sand, or other abrasive material, at extreme speed, to unsoiled debris from items to a smooth finish. Sand Blaster also functions for delicate etching glass apart from its paint, dirt, and corrosion can easily blast by a sand blaster. In this mechanism, any small, relatively uniform particles can work like copper slag, walnut shells, steel grit, powdered abrasives, sometimes along with bits of coconut shell.

    ReplyDelete
  20. Create your own Paypal login .Me link and share it instantly with anyone: friends, customers, or partners. If you don't already have a PayPal account, signing up is fast and free. And you can start accepting money …

    ReplyDelete
  21. Thanks for sharing that information, Geek Squad Tech Support is a globally recognized tech support provider, providing various support services for personal computer, gadgets, home repair and much more. We have successfully provided support services for nearly two million customers and the count has been increasing every other day.
    Please follow this link to know more about PayPal Account Login.
    PayPal Account Login is one of the best, user-friendly payment platforms. Moreover, it facilitates payments that take place via online transfers between different parties.

    ReplyDelete

  22. Assignment helper online

    Who is the best assignment helper online? Best Assignment Experts is the one-stop solution for all academic Assignment helper online
    , essays, thesis, dissertation, and coursework writing. We are a team of + 150 PhD.

    ReplyDelete
  23. Are you facing login problems with your PayPal login account? If yes! Then refer to the solutions that are mentioned below. paypal prepaid log in
    So, stay with us. We are a self-dependent technical help service provider for Computer and other devices related issues. Our experienced & certified experts are available 24*7 for you. Our technicians will be always there to help you.
    If you are having trouble while using canon printer on your device and you have tried every solution to fix the issue, then the last thing you are left with is to uninstall and re-install the Canon Printer driver. So, in this article, we have clearly discussed how to uninstall the printer on a Mac. This will be followed by a discussion on the re-installation process that can be easily done via canon.com/ijsetup canon,com/ijsetup
    123.hp.com/setup 5255 and drivers on each mobile device or computer you want to print from. Add the printer to the new device.
    The streaming of video content online is trendy today as people move to modern entertainment. They subscribe to various streaming services like Netflix, Hulu, etc. Among other things, Amazon Prime is one such streaming service. This service not only allows you to stream videos but also allows you to utilise many other features. And this is all possible by getting amazon.com/code and redeeming it. how to use amazon discount code and redeeming it.
    However, to carry on with this process, you must be assured that it is not more than 7 days since you have aol sign in now. In case it is more than 7 days, then you will not be able to get your hands on those emails. Follow the simple procedure given below to www.aol.com offical
    There are lots of secure services provided by Google that users can use whenever they use their account. But sometimes users also face numerous problems when trying to sign in to their Google account and forgetting the password is one of those. In this article, you will learn about the step-by-step process to Google Account Recovery.
    However, there is one necessary that plays an important role here is that without having a Cash App account and without doing square cash app login, you will not be able to move ahead in the process. So, in today's post, we shall learn the ways to create as well as do cash app support.
    You will need to locate the wps pin hp printer in order to connect to any other device.

    ReplyDelete
  24. www.amazon.com/mytvYou can now watch Amazon Prime Videos on your TV and mobile devices. Amazon Prime members are eligible to receive unlimited access to thousands more Prime Video titles for no additional charge. ToAmazon Prime Video activationAfter signing in, you will receive an Amazon mytv code.Amazon.com/mytvEnter the amazon activation code in your smartphone or laptop
    amazon.com/mytv
    amazon.com/mytv
    amazon.com/code
    primevideo/mytv

    ReplyDelete
  25. With metropcs payment, you can pay your bill, get an immediate refill, activate your profile, manage your current profile, and more.
    metropcs payment | metro pcs refill

    ReplyDelete
  26. Looking for Cricket Clothing? Buy Online Cricket Clothing of All Sizes like Men, Youth, Boys, Kids and Junior Available at affordable price at NZ Cricket Store. We provide branded Cricket Clothing of top quality in New Zealand.

    ReplyDelete
  27. Ready assignments are available just send us message by typing write my assignment for me.

    ReplyDelete
  28. Amazing decision to rent a slingshot and have a fun unforgettable ride to 5th ave and Naples Pier. This place carries stick shift and Automatic Slingshot Rental. Friendly professional staff and easy check out. Highly recommend Slingshot Rental Miami Beach!!!

    ReplyDelete
  29. MBBS in Philippines fee structure for UV Gullas College of Medicine fees structure is considered to affordable by most students who wish to study medicine in Philippines. The Philippines Medical college offers world class medical education at reasonable price. The top reasons most students choose a foreign country is quality of education is better in affordable cost. UV Gullas College of medicine fee structure for academic year 2021 is comparatively affordable to premium medical colleges accepting international students.


    ReplyDelete
  30. DAVAO MEDICAL SCHOOL FOUNDATION has the main aim is to provide quality medical education and training so that the medicinal solutions may grow in both the rural and urban parts of the country.

    ReplyDelete
  31. It’s actually a nice and helpful piece of spots. I am happy that you simply shared this useful game with us. Please keep enjoying yourself with us.Play Online Rummy

    ReplyDelete
  32. Really wonderful blog! Thanks for taking your valuable time to share this with us. Keep us updated with more such blogs.

    Best IAS Coaching in Mumbai

    ReplyDelete
  33. Explore the Best Website Designing, Website Development, PHP and Digital Marketing Company in Ambala Cantt. We help companies to drive growth through optimizing digital channels.
    PHP Training In Ambala | PHP Course In Ambala

    ReplyDelete
  34. www.amazon.com/mytv You have just received another Amazon device. What do you do? You will need to figure out how to connect your devices with Prime so that you can watch and tune into select Prime video content from anywhere. Simply create an amazon account and activate it using the amazon my TV activation code.
    amazon.com/mytv
    amazon.com/redeem
    amazon.com/mytv

    ReplyDelete
  35. We already stated that you don’t need any additional contraptions to be successful.Watch Amazon Prime VideoIf you have a streaming device. You can watch Amazon Prime Video on the Streaming device by following these simple and quick steps:
    amazon.com/redeem
    primevideo/mytv
    amazon.com/code

    ReplyDelete
  36. The assignment papers given by corporate administration law assignment help are the most ideal way for a student can find out with regards to their coursework as each multifaceted point that they need to understand are clarified in the actual assignment that moonlights as an incredible reference study material before the test. online assignment help

    ReplyDelete

Post a Comment

Popular posts from this blog

Snippet: align a TextView around an image

NotificationListenerService and kitkat