zoukankan      html  css  js  c++  java
  • Handler应用3 — 与Activity不同一线程

    MainActivity:

     1 package com.example.handlerthread;
     2 
     3 import android.os.Bundle;
     4 import android.os.Handler;
     5 import android.os.HandlerThread;
     6 import android.os.Looper;
     7 import android.os.Message;
     8 import android.annotation.SuppressLint;
     9 import android.app.Activity;
    10 import android.content.Intent;
    11 import android.view.Menu;
    12 
    13 @SuppressLint("HandlerLeak")
    14 public class MainActivity extends Activity {
    15 
    16     protected void onCreate(Bundle savedInstanceState) {
    17         super.onCreate(savedInstanceState);
    18         setContentView(R.layout.activity_main);
    19         
    20         //声明一个Handler线程
    21         HandlerThread hdt = new HandlerThread("myHandlerThread");
    22         //在getLooper()之前要先start线程!!!
    23         hdt.start();
    24         MyHandler myhandler = new MyHandler(hdt.getLooper());
    25         //得到handler的Message
    26         Message msg = myhandler.obtainMessage();
    27 
    28         //bundle用于数据打包传送
    29         Bundle bundle = new Bundle();
    30         bundle.putInt("age", 20);
    31         bundle.putString("name", "Human");
    32         bundle.putFloat("Score", 99.9f);
    33         //Message的setData
    34         msg.setData(bundle);
    35         //把msg送到Target处(生产msg的handler处)
    36         msg.sendToTarget();
    37 
    38     }
    39 
    40     class MyHandler extends Handler {
    41         public MyHandler() {
    42         }
    43         //构造函数,参数为Looper
    44         public MyHandler(Looper looper) {
    45             super(looper);
    46         }
    47         
    48         //重写父类的handleMessage方法
    49         //当handler得到msg后就执行handleMessage方法
    50         public void handleMessage(Message msg) {
    51             Bundle bd = msg.getData();
    52             int age = bd.getInt("age");
    53             System.out.println(age);
    54         }
    55     }
    56     public boolean onCreateOptionsMenu(Menu menu) {
    57         // Inflate the menu; this adds items to the action bar if it is present.
    58         getMenuInflater().inflate(R.menu.activity_main, menu);
    59         return true;
    60     }
    61 }
  • 相关阅读:
    Babel下的ES6兼容性与规范
    链接属性rel=’external’、rel=’nofollow’、rel=’external nofollow’三种写法的区别
    Art-template模板
    常用 Git 命令清单
    四种常见的 POST 提交数据方式
    前端面试题
    素数筛法
    编程之美 2.12 快速寻找满足条件的两个数 解法三证明 (算法导论 第二版 2.3-7 在n个元素的集合S中找到两个和为x的元素)
    NOIP1996 提高组 挖地雷
    全排列生成算法
  • 原文地址:https://www.cnblogs.com/humanchan/p/3020845.html
Copyright © 2011-2022 走看看