1,
activity1àactivity2,再返回到activity1时,activity2一定会调用onDestory,但不一定finalize。
2,
handler 和thread通常作为activity2的成员变量。activity2 被释放的时候,handler 一定会被释放,但thread不会释放。所以handler绝对是安全的,不会有垃圾。
3,
在activity2的onDestory里加上thread.getLooper().quit();
activity2退出时,thread就会停止(但是需要把thread当前动作跑完)
- package com.mp;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.HandlerThread;
- public class MyThread2 extends Activity {
- private Handler handler = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- HandlerThread handlerThread = new HandlerThread("myHandlerThread");
- handlerThread.start();
- handler = new Handler(handlerThread.getLooper());
- handler.post(new MyRunnable());
- System.out.println("Oncreate---The Thread id is :"
- Thread.currentThread().getId());
- setContentView(R.layout.main);
- }
- private class MyRunnable implements Runnable {
- public void run() {
- System.out.println("Runnable---The Thread is running");
- System.out.println("Runnable---The Thread id is :"
- Thread.currentThread().getId());
- try {
- Thread.sleep(6000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
复制代码
在这个demo中,用到了HandlerThread,在HandlerThread对象中可以通过getLooper方法获取一个Looper对象控制句柄,我们可以将其这个Looper对象映射到一个Handler中去来实现一个线程同步机制。于是就有以下结果;
1:控制台的输出: Oncreate---The Thread id is :1
Runnable---The Thread is running
Runnable---The Thread id is :10
2:程序启动后,我们立刻看到main.xml中的内容。
这样就达到了多线程的结果。