您的位置:首页 > 移动开发 > Android开发

android每隔5s显示时间

2015-11-16 13:13 585 查看
package com.example.time_1;

import java.util.zip.DataFormatException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

private static final int msgKey1 = 1;
private TextView time;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (TextView) findViewById(R.id.time);
new TimeThread().start();

}

public class TimeThread extends Thread {
@Override
public void run() {
do {
try {
Thread.sleep(5000);// //每隔5s显示时间
Message msg = new Message();
msg.what = msgKey1;
mHandler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
}

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case msgKey1:
long sysTime = System.currentTimeMillis();
CharSequence stsTimeStr = DateFormat
.format("hh:mm:ss", sysTime);
time.setText(stsTimeStr);
break;
default:
break;

}
}
};
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >

<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="107dp"
android:layout_marginTop="177dp"
android:text="@string/hello_world" />

</RelativeLayout>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 时间