Android消息机制——时钟显示和异步处理工具类(AsyncTask)
1. 时钟显示
定义布局文件——activity_my_analog_clock_thread_demo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.contactsdemo.MyAnalogClockThreadDemo" > <AnalogClock
android:id="@+id/myAnalogClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout>
定义Activity程序,进行操作
package com.example.contactsdemo; import java.text.SimpleDateFormat;
import java.util.Date; import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView; public class MyAnalogClockThreadDemo extends ActionBarActivity {
private TextView info = null; //文本显示组件
private static final int SET = 1; //线程标记
private Handler handler = new Handler(){ @Override
public void handleMessage(Message msg) {
switch(msg.what){
case SET: //判断标志位
MyAnalogClockThreadDemo.this.info.
setText("当前时间为:"+msg.obj.toString()); //设置显示信息
}
} };
private class ClockThread implements Runnable{ @Override
public void run() {
while(true){
Message msg = MyAnalogClockThreadDemo.this.handler
.obtainMessage(MyAnalogClockThreadDemo.SET,
new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())); //实例化Message
MyAnalogClockThreadDemo.this.handler.sendMessage(msg); //发送消息
try {
Thread.sleep(1000); //延迟1秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} } @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_analog_clock_thread_demo);
this.info = (TextView) super.findViewById(R.id.info); //取得组件
new Thread(new ClockThread()).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.my_analog_clock_thread_demo, 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);
}
}
2. 异步处理工具类:AsyncTask——实现进度条
定义布局文件——activity_my_async_task_demo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.contactsdemo.MyAsyncTaskDemo" > <ProgressBar
android:id="@+id/bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"/>
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> </LinearLayout>
定义Activity程序,显示进度条
package com.example.contactsdemo; import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
import android.widget.TextView; public class MyAsyncTaskDemo extends ActionBarActivity {
private ProgressBar bar = null; //进度条组件
private TextView info = null; //文本显示组件 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_async_task_demo);
this.bar = (ProgressBar) super.findViewById(R.id.bar);
this.info = (TextView) super.findViewById(R.id.info);
ChildUpdate child = new ChildUpdate(); //子任务对象
child.execute(100); //休眠时间
} private class ChildUpdate extends AsyncTask<Integer, Integer, String>{ @Override
protected void onPostExecute(String result) { //任务执行完后执行
MyAsyncTaskDemo.this.info.setText(result); //设置文本
} @Override
protected void onProgressUpdate(Integer... values) { //每次更新后的数值
MyAsyncTaskDemo.this.info.setText("当前进度是:"+values[0]); //更新文本信息
} @Override
protected String doInBackground(Integer... arg0) { //处理后台任务
for(int i=0;i<100;i++){ //进度条累加
MyAsyncTaskDemo.this.bar.setProgress(i); //设置进度
this.publishProgress(i); //传递每次更新的内容
try {
Thread.sleep(arg0[0]); //延缓执行
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "执行完毕!";
} }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my_async_task_demo, 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);
}
}
Android消息机制——时钟显示和异步处理工具类(AsyncTask)的更多相关文章
- Android消息机制
每一个Android应用在启动的时候都会创建一个线程,这个线程被称为主线程或者UI线程,Android应用的所有操作默认都会运行在这个线程中. 但是当我们想要进行数据请求,图片下载,或者其他耗时操作时 ...
- Android消息机制不完全解析(上)
Handler和Message是Android开发者常用的两个API,我一直对于它的内部实现比较好奇,所以用空闲的时间,阅读了一下他们的源码. 相关的Java Class: androi ...
- Android 消息机制 (Handler、Message、Looper)
综合:http://blog.csdn.net/dadoneo/article/details/7667726 与 http://android.tgbus.com/Android/androidne ...
- Android开发之漫漫长途 ⅥI——Android消息机制(Looper Handler MessageQueue Message)
该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...
- Android开发之漫漫长途 Ⅶ——Android消息机制(Looper Handler MessageQueue Message)
该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解And ...
- Android消息机制探索(Handler,Looper,Message,MessageQueue)
概览 Android消息机制是Android操作系统中比较重要的一块.具体使用方法在这里不再阐述,可以参考Android的官方开发文档. 消息机制的主要用途有两方面: 1.线程之间的通信.比如在子线程 ...
- Android消息机制1-Handler(Java层)(转)
转自:http://gityuan.com/2015/12/26/handler-message-framework/ 相关源码 framework/base/core/java/andorid/os ...
- 每日一问:Android 消息机制,我有必要再讲一次!
坚持原创日更,短平快的 Android 进阶系列,敬请直接在微信公众号搜索:nanchen,直接关注并设为星标,精彩不容错过. 我 17 年的 面试系列,曾写过一篇名为:Android 面试(五):探 ...
- 深入理解Android消息机制
在日常的开发中,Android 的消息机制作为系统运行的根本机制之一,显得十分的重要. 从 Handler 发送消息开始 查看源码,Handler的post.send方法最终都会走到 public f ...
随机推荐
- MySql 5.6 查询日志
记录所有查询的方法 打开My.ini 在 [mysqld]下面写 general_log= ON; log_output= TABLE; 然后保存重启mysql 最后在mysql库下 general_ ...
- 【原创译文】基于Docker和Rancher的超融合容器云架构
基于Docker和Rancher的超融合容器云架构 ---来自Rancher和Redapt 超融合架构在现代数据中心是一项巨大的变革.Nutanix公司发明了超融合架构理论,自从我听说他们的“iPho ...
- hadoop-1.2.0源码编译
以下为在CentOS-6.4下hadoop-1.2.0源码编译步骤. 1. 安装并且配置ant 下载ant,将ant目录下的bin文件夹加入到PATH变量中. 2. 安装git,安装autoconf, ...
- socket 粘包问题(转)
https://www.v2ex.com/t/234785#reply3 1. 面向字节流的 IO 都有这个问题. socket 中 tcp 协议是面向流的协议,发送方发送和接收方的接收并不是一一对应 ...
- 理解OAuth 2.0 -摘自网络
OAuth是一个关于授权(authorization)的开放网络标准,在全世界得到广泛应用,目前的版本是2.0版. 本文对OA ...
- Gradle 1.3之前的Publishing artifacts
在Gradle1.3之前,Publishing artifacts是使用uploadConfigurationName来publish 声明artifacts是靠使用 build.gradle art ...
- LightOJ 1282 Leading and Trailing (快数幂 + 数学)
http://lightoj.com/volume_showproblem.php?problem=1282 Leading and Trailing Time Limit:2000MS Me ...
- IllegalStateException
例1 public static void main(String[]sdf){ List<String> list = new ArrayList<String>(); li ...
- J2EE项目相对路径、绝对路径获取
String path = getServletContext().getRealPath("/"); 这将获取web项目的全路径. this.getClass().getClas ...
- 彻底解决cookie欺骗(有问题)
不要在公共场登陆 自己重要的用户名和密码: 不用的时候,[关闭浏览器],只点[退出],还是会有安全隐患.--没有绝对的安全由于http的无状态性,总不能每次访问页面都要输入用户名和密码,所以为了保持状 ...