开发环境为android4.1.
Handler使用例1
这个例子是最简单的介绍handler使用的,是将handler绑定到它所建立的线程中.
本次实验完成的功能是:单击Start按钮,程序会开始启动线程,并且线程程序完成后延时1s会继续启动该线程,每次线程的run函数中完成对界面输出nUpdateThread...文字,不停的运行下去,当单击End按钮时,该线程就会停止,如果继续单击Start,则文字又开始输出了。
软件界面如下:
实验主要部分代码和注释:
MainActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView text_view = null;
private Button start = null;
private Button end = null;
//使用handler时首先要创建一个handler
Handler handler = new Handler();
//要用handler来处理多线程可以使用runnable接口,这里先定义该接口
//线程中运行该接口的run函数
Runnable update_thread = new Runnable()
{
public void run()
{
//线程每次执行时输出"UpdateThread..."文字,且自动换行
//textview的append功能和Qt中的append类似,不会覆盖前面
//的内容,只是Qt中的append默认是自动换行模式
text_view.append("/nUpdateThread...");
//延时1s后又将线程加入到线程队列中
handler.postDelayed(update_thread, 1000);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_view = (TextView)findViewById(R.id.text_view);
start = (Button)findViewById(R.id.start);
start.setOnClickListener(new StartClickListener());
end = (Button)findViewById(R.id.end);
end.setOnClickListener(new EndClickListener());
}
private class StartClickListener implements OnClickListener
{
public void onClick(View v) {
// TODO Auto-generated method stub
//将线程接口立刻送到线程队列中
handler.post(update_thread);
}
}
private class EndClickListener implements OnClickListener
{
public void onClick(View v) {
// TODO Auto-generated method stub
//将接口从线程队列中移除
handler.removeCallbacks(update_thread);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="200dip"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/start"
/>
<Button
android:id="@+id/end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/end"
/>
</LinearLayout>
单击Start按钮后,更新的进度条结果如下(怎么感觉4.1版本android进度条那么小呢?不懂该怎么设置):
实验主要部分代码和注释:
MainActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private ProgressBar progress_bar = null;
private Button start = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress_bar = (ProgressBar)findViewById(R.id.progress_bar);
start = (Button)findViewById(R.id.start);
start.setOnClickListener(new StartOnClickListenr());
}
private class StartOnClickListenr implements OnClickListener
{
public void onClick(View v) {
// TODO Auto-generated method stub
//让进度条显示出来
progress_bar.setVisibility(View.VISIBLE);
//将线程加入到handler的线程队列中
update_progress_bar.post(update_thread);
}
}
//创建一个handler,内部完成处理消息方法
Handler update_progress_bar = new Handler()
{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
//显示进度条
progress_bar.setProgress(msg.arg1);
//重新把进程加入到进程队列中
update_progress_bar.post(update_thread);
}
};//不加这个分号则不能自动添加代码
Runnable update_thread = new Runnable()
{
int i = 0;
public void run() {
// TODO Auto-generated method stub
i += 10;
//首先获得一个消息结构
Message msg = update_progress_bar.obtainMessage();
//给消息结构的arg1参数赋值
msg.arg1 = i;
//延时1s,java中的try+catch用来排错处理
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
//把消息发送到消息队列中
update_progress_bar.sendMessage(msg);
if(i == 100)
//把线程从线程队列中移除
update_progress_bar.removeCallbacks(update_thread);
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
<Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="@string/start"
/>
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:layout_alignParentTop="true"
style="?android:attr/progressBarStyleHorizontal"
android:visibility="gone"
/>
</RelativeLayout>
MainActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
public class MainActivity extends Activity {
//新建一个handler
private Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//将runnable加载到handler的线程队列中去
// handler.post(r);
Thread t = new Thread(r);
t.start();
setContentView(R.layout.activity_main);
//打印activtiy线程信息
System.out.println("activity_id---->"+Thread.currentThread().getId());
System.out.println("activity_name---->"+Thread.currentThread().getName());
}
Runnable r = new Runnable()
{
public void run() {
// TODO Auto-generated method stub
//打印新建线程信息
System.out.println("handler_id---->"+Thread.currentThread().getId());
System.out.println("handler_name---->"+Thread.currentThread().getName());
//延时10s,为了观察主界面中内容出现的时间
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("activity_ID---->"+Thread.currentThread().getId());
//新建一个HanderThread对象,该对象实现了用Looper来处理消息队列的功能
HandlerThread handler_thread = new HandlerThread("handler_thread");
handler_thread.start();
//MyHandler类是自己继承的一个类,这里采用hand_thread的Looper来初始化它
MyHandler my_handler = new MyHandler(handler_thread.getLooper());
//获得一个消息msg
Message msg = my_handler.obtainMessage();
//采用Bundle保存数据,Bundle中存放的是键值对的map,只是它的键值类型和数据类型比较固定而已
Bundle b = new Bundle();
b.putString("whether", "晴天");
b.putInt("temperature", 34);
msg.setData(b);
//将msg发送到自己的handler中,这里指的是my_handler,调用该handler的HandleMessage方法来处理该mug
msg.sendToTarget();
}
class MyHandler extends Handler
{
//空的构造函数
public MyHandler()
{}
//以Looper类型参数传递的函数,Looper为消息泵,不断循环的从消息队列中得到消息并处理,因此
//每个消息队列都有一个Looper,因为Looper是已经封装好了的消息队列和消息循环的类
public MyHandler(Looper looper)
{
//调用父类的构造函数
super(looper);
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
System.out.println("Handler_ID---->"+Thread.currentThread().getId());
System.out.println("Handler_Name---->"+Thread.currentThread().getId());
//将消息中的bundle数据取出来
Bundle b = msg.getData();
String whether = b.getString("whether");
int temperature = b.getInt("temperature");
System.out.println("whether= "+whether+" ,temperature= "+temperature);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
新闻热点
疑难解答
图片精选