码迷,mamicode.com
首页 > 其他好文 > 详细

Handler的基本使用

时间:2015-02-24 15:10:23      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:handler的基本使用

一、基本知识点

1、Intent intent = new Intent();//打开浏览器的
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));


2、SystemClock.sleep(20000);//睡眠20秒,用来掩饰想赢一场


3、耗时的操作都应该子线程中做
联网获取数据
大文件的拷贝
都需要放置在子线程来操作


onCreate()  按钮点击回调事件、对于显示的操作都是在主线程里面运行。UI线程。


4、handler的使用
new Handler();


Message msg = new Message();
   msg.what = UPDATE_DISPLAY;//设置消息的唯一识别
   msg.obj = i;
   mHandler.sendMessage(msg)



二、示例代码

package com.example.handlertest;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {


public TextView tv_num;

public static final int UPDATE_NUMBER = 0;

public int i = 0;

public Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == UPDATE_NUMBER){
int i = (Integer) msg.obj;

tv_num.setText(i + "");
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

tv_num = (TextView) findViewById(R.id.tv_number);



}



public void add(View view){
new Thread(){
@Override
public void run() {
super.run();

while(i < 100){
SystemClock.sleep(1000);
i += 1;


Message msg = new Message();
msg.what = UPDATE_NUMBER;
msg.obj = i;
handler.sendMessage(msg);
}

}
}.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

Handler的基本使用

标签:handler的基本使用

原文地址:http://blog.csdn.net/xlgen157387/article/details/43925221

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!