Android Service ANR

1.當在Activity 的onCreate方法中啓動一個服務,服務裏面是一個死循環。=》主界面無法繪出,點擊手機鍵盤的返回按鈕會報ANR錯誤。

2.當在Activity 的onCreate方法中啓動一個線程,線程裏面啓動一個服務,服務裏面是一個死循環。=》主界面可以繪出 但會報ANR錯誤。

3.當給按鈕設置了一個點擊事件,單擊方法中啓動了一個線程,線程內啓動了一個服務,服務裏面是一個死循環。=》5秒後會報ANR錯誤

4.當給按鈕設置了一個點擊事件,單擊方法中啓動了一個服務,      服務裏面是一個死循環。=》點擊手機鍵盤的返回按鈕會報ANR錯誤

 

不報錯的是

給按鈕設置了一個點擊事件,單擊方法中啓動了一個線程,線程內是無限循環。不會報錯。即使activity被銷燬了,線程依然會執行。如果想讓線程銷燬,則可以在

onDestroy()方法中加入System.exit();

 

誤區:很多人以爲service 能執行耗時的操作,這是一個誤區,service 中不能執行耗時的操作,它也屬於UI主線程,要執行耗時操作可以使用IntentService

http://blog.csdn.net/zhf198909/article/details/6906786

IntentService和Service的重要區別是,IntentService中 onHandleIntent(Intent intent)的代碼執行完畢後,會自動停止服務,執行onDestroy()方法

http://android.blog.51cto.com/268543/528166

 

如果在Service中啓動了一個無限循環線程,如果想停止此線程的執行。需要先停止服務,然後再執行System.exit()或者android.os.Process.killProcess(android.os.Process.myPid())終止線程;

[java] view plain copy
 print?
  1. public class MainActivity extends Activity implements OnClickListener{  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState)   
  5.     {  
  6.         super.onCreate(savedInstanceState);  
  7.         setContentView(R.layout.main);   
  8.         Button button = (Button) this.findViewById(R.id.button);  
  9.         button.setOnClickListener(this);  
  10.          
  11.     }  
  12.     @Override  
  13.     public void onClick(View v)  
  14.     {  
  15.         // TODO Auto-generated method stub  
  16.           
  17. //        new Thread(new MyThread()).start();        
  18.         Intent intent = new Intent(MainActivity.this,SqkService.class);  
  19.         MainActivity.this.startService(intent);  
  20.   
  21.           
  22.     }  
  23.   
  24.     @Override  
  25.     public void onDestroy()  
  26.     {  
  27.         super.onDestroy();  
  28.         Intent  intent = new Intent(MainActivity.this,SqkService.class);  
  29. //      銷燬service中的無限循環線程的方式一:先停止線程,再殺掉進程,2句代碼缺一不可  
  30.   
  31.         this.stopService(intent);  
  32.         System.exit(0);  
  33. //      銷燬service中的無限循環線程的方式二:先停止線程,再殺掉進程,2句代碼缺一不可  
  34.           
  35. //      this.stopService(intent);  
  36. //      android.os.Process.killProcess(android.os.Process.myPid());  
  37.     }  
  38. }  

轉載地址:http://blog.csdn.net/sqk1988/article/details/6788165
 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章