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.