package com.example.handlerdemowjj;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
 // 另外的线程
 private static final int MSG_SUCCESS = 0;// 获取成功的标识
 private static final int MSG_FAILURE = 1;// 获取失败的标识
 private Thread mThread;
 TextView tv;

 private Handler mHandler = new Handler(){

  public void handleMessage(Message msg) {// 此方法在ui线程运行
   switch (msg.what) {
   case MSG_SUCCESS:
    Log.v("logcat", "MSG_SUCCESS" + Thread.currentThread());
    Log.v("logcat", "MSG_SUCCESS_ID:"
      + Thread.currentThread().getId() + ",name="
      + Thread.currentThread().getName());
    Toast.makeText(getApplication(), "成功", Toast.LENGTH_LONG)
      .show();
    tv.setText("new.成功");
    break;

   case MSG_FAILURE:
    Log.v("logcat", "MSG_FAILURE" + Thread.currentThread());
    Toast.makeText(getApplication(), "失败", Toast.LENGTH_LONG)
      .show();
    break;
   }
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  tv = (TextView) findViewById(R.id.tv);

  Runnable runnable = new Runnable() {
   @Override
   public void run() {
    //这是新的线程,可在这儿处理耗时的操作,更新不了UI界面的操作的

    Log.v("logcat",
      "new-Thread.currentThread()=" + Thread.currentThread());
    Log.v("logcat", "new-Thread.currentThread().getId()="
      + Thread.currentThread().getId() + ",name="
      + Thread.currentThread().getName());

    int i = 0;
    if (i == 0) {
     mHandler.obtainMessage(MSG_SUCCESS).sendToTarget();// 获取成功
     
    } else {
     mHandler.obtainMessage(MSG_FAILURE).sendToTarget();// 获取失败
    }

   }
  };
  if (mThread == null) {

   Toast.makeText(getBaseContext(), "mThread == null",
     Toast.LENGTH_LONG).show();
   mThread = new Thread(runnable);
   mThread.start();// 线程启动
  } else {
   Toast.makeText(getBaseContext(), "thread_started",
     Toast.LENGTH_LONG).show();
  }

 }

}

更多相关文章

  1. android中view组件使用详解
  2. Android设备信息管理工具类
  3. android > WiFi > 新建连接
  4. Android使用View类动画
  5. android获取控件的几种方法
  6. android studio获取SH1码
  7. 后续:优化
  8. Android之获取当前Activity名称
  9. android 从系统相册获取一张图片

随机推荐

  1. android EditText限制只能输入2位小数的
  2. android的网络访问
  3. Android中全屏无标题设置
  4. Android(安卓)异步网络请求及协调CountDo
  5. android Fragments详解【2】
  6. android中关闭返回键
  7. android 随手记 videoview循环播放网络视
  8. android notifyDataSetChanged不管用
  9. Android(安卓)生成xml文件
  10. Android(安卓)Studio 2中通过getDeclared