本文共 2313 字,大约阅读时间需要 7 分钟。
简单例子
package com.peidw;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.HandlerThread;import android.os.Message;import android.text.Html;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;/** * * @author peidw * */public class HandlerThreadActivity extends Activity { private TextView mt; private Handler mcHandler=new Handler(){ @Override public void handleMessage(Message msg) { mt.setText(Html.fromHtml((String)msg.obj)); mcHandler.post( update_thread); } }; private boolean isUpdateInfo=true; //与UI线程管理的handler private static final int MSG_UPDATE_INFO = 0x110; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler_thread); //创建后台线程 mt = (TextView) findViewById(R.id.id_textview); mcHandler.post(update_thread); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.handler_thread, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void initBack(){ Log.i ("AA----->","-----------------initBack"); //ht=new HandlerThread("check-message-coming"); //ht.start(); Log.i ("AA----->","-----------------isUpdateInfo="+isUpdateInfo); } Runnable update_thread = new Runnable() { int i=0; public void run(){ Message msg = mcHandler.obtainMessage(); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String result = "实时更新中,当前大盘指数:%d"; result = String.format(result, (int) (Math.random() * 3000 + 1000)); msg.obj=result; mcHandler.sendMessage(msg); if(i>100){ mcHandler.removeCallbacks(update_thread); } } }; }
layout
转载地址:http://ylvwn.baihongyu.com/