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 }
  • 相关阅读:
    echarts雷达图点击事件 包含(2.x,3.85,4.02)测试
    字体图标制作
    通过php动态传数据到highcharts
    smartgit试用到期不用序列号怎么继续使用
    项目的ip地址更改,用git从远程提取代码出现错误,提示为 network error connection timed out
    OC学习4——OC新特性之块(Block)
    OC学习3——C语言特性之指针
    OC学习2——C语言特性之函数
    OC学习1——基本数据类型
    JVM 内存的那些事
  • 原文地址:https://www.cnblogs.com/humanchan/p/3020845.html
Copyright © 2011-2022 走看看