ANR exception, anr

Source: Internet
Author: User

ANR exception, anr
ANR exception

I. Introduction

Solution: Do not write time-consuming operations in the main thread.

 

Ii. code example

 

Click the button and keep clicking.

An anr exception occurs.

Code

/Anr/src/anr/MainActivity. java

1 package anr; 2 3 4 5 6 7 import com. example. anr. r; 8 9 import android. app. activity; 10 import android. content. intent; 11 import android. OS. bundle; 12 import android. view. view; 13 import android. view. view. onClickListener; 14 import android. widget. button; 15 16 17 18 public class MainActivity extends Activity {19 private Button btn_openActivty; // create a button object 20 protected void onCreate (Bundle savedInstanceState) {21 super. onCreate (savedInstanceState); // action of the parent class 22 setContentView (R. layout. activity_main); // introduce the interface named activity_main 23 btn_openActivty = (Button) findViewById (R. id. btn_openActivity); // find the button24/* id of btn_openActivity /*25 * time-consuming operations are performed in the main thread (UI thread). 26 * The interface cannot respond to the input event, and 27 * will cause an ANR exception (more than 6 seconds)28 */29 btn_openActivty.setOnClickListener (new OnClickListener () {// set the button to listen to 30 31 @ Override32 public void onClick (View v) {// onclick event 33 // TODO Auto-generated method stub34 try {35 Thread. sleep (6000); 36} catch (Exception e) {37 // TODO: handle exception38 e. printStackTrace (); 39}40 Intent intent = new Intent (); // initialize intent41 intent. setClass (MainActivity. this, Activity01.class); // connect 42 startActivity (intent); // enable activity43} 44}); 45} 46}

Solution: Do not write time-consuming operations in the main thread.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.