博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android之Handler
阅读量:5240 次
发布时间:2019-06-14

本文共 6243 字,大约阅读时间需要 20 分钟。

1.Handler默认情况下与主线程处于同一线程

public class MainActivity extends Activity {    private Button startButton = null;    private Button endButton = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        startButton = (Button) findViewById(R.id.startButton);        endButton = (Button) findViewById(R.id.endButton);        startButton.setOnClickListener(new StartButtonListener());        endButton.setOnClickListener(new EndButtonListener());        /*         * if (savedInstanceState == null) {         * getSupportFragmentManager().beginTransaction() .add(R.id.container,         * new PlaceholderFragment()).commit(); }         */    }    class StartButtonListener implements OnClickListener {        @Override        public void onClick(View v) {            System.out.println(Thread.currentThread().getId() + " Start");            handler.post(updateThread);        }    }    class EndButtonListener implements OnClickListener {        @Override        public void onClick(View v) {            System.out.println(Thread.currentThread().getId() + " End");            handler.removeCallbacks(updateThread);        }    }    Handler handler = new Handler();    Runnable updateThread = new Runnable() {        @Override        public void run() {            System.out                    .println(Thread.currentThread().getId() + " UpdateThread");            handler.postDelayed(updateThread, 3000);        }    };

 

2.通过Handler实现进度条

public class MainActivity extends Activity {    ProgressBar bar = null;    Button startButton = null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        System.out.println("主线程ID:"+Thread.currentThread().getId());        bar = (ProgressBar) findViewById(R.id.bar);        startButton = (Button) findViewById(R.id.startButton);        startButton.setOnClickListener(new ButtonListener());        /*         * if (savedInstanceState == null) {         * getSupportFragmentManager().beginTransaction() .add(R.id.container,         * new PlaceholderFragment()).commit(); }         */    }    class ButtonListener implements OnClickListener {        @Override        public void onClick(View v) {            bar.setVisibility(View.VISIBLE);            updateBarHandler.post(updateThread);        }    }    //使用匿名内部类    Handler updateBarHandler = new Handler() {        //可传递参数        @Override        public void handleMessage(Message msg) {            bar.setProgress(msg.arg1);            updateBarHandler.post(updateThread);        }    };    //线程类,该类使用匿名内部类的方式进行声明    Runnable updateThread = new Runnable() {        int i = 0;        @Override        public void run() {            System.out.println("Begin Thread");            System.out.println("Handler线程ID:"+Thread.currentThread().getId());            i = i + 10;            //得到一个消息,Message类是有Android操作系统提供的            Message msg = updateBarHandler.obtainMessage();            //将msg对象的arg1参数的值设置为i,用arg1和arg2这两个            //成员变量传递值,优点是消耗性能小            msg.arg1 = i;            try {                Thread.sleep(1000);            } catch (Exception e) {                e.printStackTrace();            }            updateBarHandler.sendMessage(msg);            if (i >= 100) {                updateBarHandler.removeCallbacks(updateThread);            }        }    };

 

3.Handler通过post执行Runnable(还是与主线程处于同一线程)

public class MainActivity extends Activity {    private Handler handler = new Handler();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //handler线程和主线程在同一线程        handler.post(r);        /*Thread t=new Thread(r);        t.start();*/                System.out.println("activity-->" + Thread.currentThread().getId());        System.out.println("activityname-->" + Thread.currentThread().getId());        /*         * if (savedInstanceState == null) {         * getSupportFragmentManager().beginTransaction() .add(R.id.container,         * new PlaceholderFragment()).commit(); }         */    }    Runnable r = new Runnable() {        @Override        public void run() {            System.out.println("handler-->" + Thread.currentThread().getId());            System.out.println("handlername-->"                    + Thread.currentThread().getName());            try {                Thread.sleep(10000);            } catch (Exception e) {                e.printStackTrace();            }        }    };

 

4.通过HandlerThread执行线程,并可通过Bundle传递参数

public class MainActivity02 extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main_activity02);        System.out.println(Thread.currentThread().getId());        //生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能,这个类由Android提供        HandlerThread handlerThread=new HandlerThread("handler_Thread");        handlerThread.start();        MyHandler myHandler=new MyHandler(handlerThread.getLooper());        Message msg=myHandler.obtainMessage();        msg.obj="abc";//通过obj存储数据        Bundle b=new Bundle();        b.putInt("age", 20);        b.putString("name", "Jhon");        msg.setData(b);//通过Bundle存储数据        msg.sendToTarget();//将msg发送到目标对象,所谓的目标对象就是生成该msg的Handler        /*if (savedInstanceState == null) {            getSupportFragmentManager().beginTransaction()                    .add(R.id.container, new PlaceholderFragment()).commit();        }*/    }    class MyHandler extends Handler{        public MyHandler(){                    }        public MyHandler(Looper looper){            super(looper);        }        @Override        public void handleMessage(Message msg){            System.out.println(msg.obj);            Bundle b=msg.getData();            System.out.println(b.getInt("age"));            System.out.println(b.getString("name"));            System.out.println("handleMessage:"+Thread.currentThread().getId());        }    }

 

转载于:https://www.cnblogs.com/zhuawang/p/3647734.html

你可能感兴趣的文章
[poj 3539] Elevator (同余类bfs)
查看>>
[tyvj2054] 四叶草魔杖 (最小生成树 状压dp)
查看>>
[译] 命名有意义的版本号2.0.0-rc1
查看>>
poj 1463树形dp 树的最小覆盖
查看>>
【转】Apache httpd.conf配置解释
查看>>
团队冲刺(第五天)
查看>>
浅谈树链剖分(C++、算法、树结构)
查看>>
FZU2121_神庙逃亡
查看>>
Kubernetes 之 MySQL 持久存储和故障转移(十一)
查看>>
HAProxy的访问控制
查看>>
Codeforces Round #349
查看>>
POJ2104 K-th Number Range Tree
查看>>
Ubuntu14.04安装GNOME3桌面
查看>>
解决:j-link V8下载器灯不亮,无法正常烧写固件
查看>>
初识面向对象
查看>>
Java反射和动态代理
查看>>
hadoop多机安装HA+YARN
查看>>
面试-数据库
查看>>
AJAX overrideMimeType作用
查看>>
spring+mybatis的多源数据库配置实战
查看>>