我是靠谱客的博主 痴情煎饼,最近开发中收集的这篇文章主要介绍Service 学习(二)Service 的 ANR 错误 ,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

[color=blue][size=x-large]1.当在Activity 的onCreate方法中启动一个服务,服务里面是一个死循环。=》主界面无法绘出,点击手机键盘的返回按钮会报ANR错误。

2.当在Activity 的onCreate方法中启动一个线程,线程里面启动一个服务,服务里面是一个死循环。=》主界面可以绘出 但会报ANR错误。

3.当给按钮设置了一个点击事件,单击方法中启动了一个线程,线程内启动了一个服务,服务里面是一个死循环。=》5秒后会报ANR错误

4.当给按钮设置了一个点击事件,单击方法中启动了一个服务, 服务里面是一个死循环。=》点击手机键盘的返回按钮会报ANR错误



不报错的是

给按钮设置了一个点击事件,单击方法中启动了一个线程,线程内是无限循环。不会报错。即使activity被销毁了,线程依然会执行。如果想让线程销毁,则可以在

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



误区:很多人以为service 能执行耗时的操作,这是一个误区,service 中不能执行耗时的操作,它也属于UI主线程,要执行耗时操作可以使用IntentService

IntentService和Service的重要区别是,IntentService中 onHandleIntent(Intent intent)的代码执行完毕后,会自动停止服务,执行onDestroy()方法

如果在Service中启动了一个无限循环线程,如果想停止此线程的执行。需要先停止服务,然后再执行System.exit()或者android.os.Process.killProcess(android.os.Process.myPid())终止线程;[/size][/color]

public class MainActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(this);

}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub

// new Thread(new MyThread()).start();
Intent intent = new Intent(MainActivity.this,SqkService.class);
MainActivity.this.startService(intent);


}

@Override
public void onDestroy()
{
super.onDestroy();
Intent intent = new Intent(MainActivity.this,SqkService.class);
// 销毁service中的无限循环线程的方式一:先停止线程,再杀掉进程,2句代码缺一不可

this.stopService(intent);
System.exit(0);
// 销毁service中的无限循环线程的方式二:先停止线程,再杀掉进程,2句代码缺一不可

// this.stopService(intent);
// android.os.Process.killProcess(android.os.Process.myPid());
}
}

最后

以上就是痴情煎饼为你收集整理的Service 学习(二)Service 的 ANR 错误 的全部内容,希望文章能够帮你解决Service 学习(二)Service 的 ANR 错误 所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部