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())終止線程;
- 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());
- }
- }
轉載地址:http://blog.csdn.net/sqk1988/article/details/6788165