Android Service ANR

来源:互联网 发布:手机淘宝怎样删除订单 编辑:程序博客网 时间:2024/05/17 22:06

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
 

 

 

 

原创粉丝点击