• 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 }
  • 相关阅读:
    出现过拟合与欠拟合的原因以及解决方案
    Oracle数据库连接生成DDL
    CentOS 7 安装 maven
    基于Spring mvc 的Websocket 开发
    HttpComponents之httpclient
    java filter 实现权限控制
    java hasmap对象的深复制实现:字节码复制和对象序列化成字符串复制比较。
    eatwhatApp开发实战(二)
    eatwhatApp开发实战(一)
    [安卓安全] 01.安卓本地数据存储:Shared Preferences安全风险浅析
  • 原文地址:https://www.cnblogs.com/humanchan/p/3020845.html
Copyright © 2020-2023  润新知