Android计时器

熟悉和掌握Android线程的使用

实验要求:

完成一个秒表,具备启停功能,正确使用工作线程完成界面刷新

分析秒表的计时是否准确,原因是什么,如何保证秒表计时准确

代码实现:

(1)Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="vertical"android:gravity="center"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="秒表"android:textSize="30dp"android:paddingTop="80dp"/><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center"><TextViewandroid:id="@+id/tv_min"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="25dp"android:text="00"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="25dp"android:text=":"/><TextViewandroid:id="@+id/tv_seconds"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="25dp"android:text="00"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="25dp"android:text=":"/><TextViewandroid:id="@+id/tv_ms"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="25dp"android:text="00"/></LinearLayout><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"><Buttonandroid:id="@+id/btn_clean"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="清零"android:textSize="20dp"/><Buttonandroid:id="@+id/btn_count"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="计时"android:textSize="20dp"/><Buttonandroid:id="@+id/btn_stop"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="停止"android:textSize="20dp"/></LinearLayout>
</LinearLayout>

(2)MainActivity.java文件

package com.example.administrator.myapplication5;import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;public class MainActivity extends Activity {private static Handler handler=new Handler();private static TextView tv_minus;private static TextView tv_seconds;private static TextView tv_ms;public static int minuts;public static int seconds;public static int mseconds;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tv_minus=(TextView)findViewById(R.id.tv_min);tv_seconds=(TextView)findViewById(R.id.tv_seconds);tv_ms=(TextView)findViewById(R.id.tv_ms);final Button btn_clean=(Button)findViewById(R.id.btn_clean);final Button btn_count=(Button)findViewById(R.id.btn_count);final Button btn_stop=(Button)findViewById(R.id.btn_stop);final Intent serviceIntent=new Intent(this,CountService.class);btn_clean.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){System.out.println("thisisatestsssss");tv_minus.setText("00");tv_seconds.setText("00");tv_ms.setText("00");}});btn_count.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){startService(serviceIntent);//显示启动service
            }});btn_stop.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){stopService(serviceIntent);//停止service
            }});}public static void UpdateGUI(int m,int s,int ms){minuts=m;seconds=s;mseconds=ms;handler.post(RefreshLable);}static Runnable RefreshLable=new Runnable() {@Overridepublic void run() {try {Thread.sleep(50);tv_minus.setText(String.format("%02d",minuts));tv_seconds.setText(String.format("%02d",seconds));tv_ms.setText(String.format("%02d",mseconds%100));} catch (InterruptedException e) {e.printStackTrace();}}};
}

(3)CountService.Java文件

package com.example.administrator.myapplication5;import android.app.Service;
import android.content.Intent;
//import android.icu.util.Calendar;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;import java.util.Calendar;/*** Created by lh on 2018/10/22.*/public class CountService extends Service {private Thread workThread;long startTime=System.currentTimeMillis();@Overridepublic void onCreate() {super.onCreate();workThread=new Thread(null,backgroundThread,"workThread");}@Overridepublic void onStart(Intent intent,int startId) {super.onStart(intent,startId);if(!workThread.isAlive()){workThread.start();}} @Overridepublic void onDestroy() {super.onDestroy();workThread.interrupt();}@Overridepublic IBinder onBind(Intent intent){return null;}private Runnable backgroundThread=new Runnable() {@Overridepublic void run() {try{while(!Thread.interrupted()){long currentTime=System.currentTimeMillis();long time=currentTime-startTime;long m=time/(1000*60);long s=time/1000;long ms=time%1000;int mi=(int)m;int si=(int)s;int msi=(int)ms;MainActivity.UpdateGUI(mi,si,msi);workThread.sleep(50);}}catch (InterruptedException e){e.printStackTrace();}}};
}

(4)AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.administrator.myapplication5"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><service android:name=".CountService"/></application></manifest>

总结:

setText()括号内应该是String类型

 

System.currentTimeMillis()函数来获取系统时间

 

 

转载于:https://www.cnblogs.com/loyolh/p/9954572.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/426442.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java学习(81):静态代码块

//静态代码块class test16 {private static final String URL;private static final String DEVICE;private static final String USER;private static final String ROOT;static test16 self;static {URL"歌谣";DEVICE"笔记本电脑";USER"root";…

linux用echo显示欢迎信息,我使用过的Linux命令之echo - 显示文本、打印信息

&#xfeff;&#xfeff;用途说明echo命令用来打印信息&#xff0c;是一个最常用的命令。在命令行中常用来打印环境变量的值&#xff0c;已确定当前环境中是否设置了指定的环境变量。在shell脚本中&#xff0c;常用来打印信息和帮助调试程序。常用参数-n 打印信息之后不换行。…

LeetCode 169. Majority Element

LeetCode 169. Majority Element 分析 难度 易 来源 https://leetcode.com/problems/majority-element/ JDK里的排序算法&#xff0c;效率就是高啊 题目 Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊…

java学习(82):静态代码块内部类

//静态代码块内部类 public class test18{private static final String URL;private static final String DEVICE;private static final String USER;private static final String ROOT;static test18 self;static {class Inner{public void printMessage(){System.out.println…

linux进程管理fork,Linux -- 进程管理之 fork() 函数

一个进程调用fork()函数后&#xff0c;系统先给新的进程分配资源&#xff0c;例如存储数据和代码的空间。然后把原来的进程的所有值都复制到新的新进程中&#xff0c;只有少数值与原来的进程的值不同。相当于克隆了一个自己。Test1for(int i 0; i<2; i){if(fork() 0)print…

java学习(83):常用基础类object

//常用基础类 public class ObjectClass {private String name;private int age;public void say(){System.out.println(name);System.out.println(age);}public void setAge(int age) {this.age age;}public int getAge() {return age;}public void setName(String name) {th…

Elasticsearch及相关插件的安装

Elasticsearch及相关插件的安装 1、安装Elasticsearch并启动服务 2、安装第三方插件 2.1、Head插件 是Elasticsearch的一个集群管理工具&#xff0c;可以通过它来查看和搜索ES的数据&#xff0c;是完全由html5编写的独立网页程序。 2.2、Bigdesk插件 是Elasticsearch的一个集群…

linux上git克隆命令,Git clone命令用法

git clone是git中常用的命令&#xff0c;其作用是将存储库克隆到新目录中。那么在git中&#xff0c;git clone具体该如何用呢?更快更轻松的学习Git,请点击Git微课git clone命令的作用是将存储库克隆到新目录中&#xff0c;为克隆的存储库中的每个分支创建远程跟踪分支(使用git…

java学习(84):object常用方法tostring,equals,hashcode

//object常用方法 public class test21 {public static void main(String[] args) {Object obj new Object();ObjectCl usr new ObjectCl();usr.setAge(6);usr.setName("歌谣");usr.say();//tostringString str usr.toString();System.out.println(str);//equalsO…

《写给大家看的设计书》(第四版)

今天读完了《写给大家看的设计书》&#xff08;第四版&#xff09;&#xff0c;Robin Williamy用浅显易懂的语言和例子&#xff0c;给我们展示了设计中的基本原则&#xff0c;以下做一个简单的记录和总结。 设计中需要遵循的四个原则&#xff0c;其实很多都是我们在设计中已经实…

linux不支持32,Visual Studio Code 1.36发布,不再支持Linux 32位

VS Code 1.36&#xff0c;即2019年6月发布的Visual Studio Code&#xff0c;已发布。新版本已更新至Electron 4.x&#xff0c;意味着它将不再在Linux 32位上运行。现在可以将文件夹从VS Code外部拖放到文件资源管理器中进行复制。 以前&#xff0c;在将文件夹放入VS Code Explo…

java学习(85):Interage包装类基本使用

测试类 public class test22 {public static void main(String[] args){int num5;Integer obj1new Integer(num);System.out.println("obj1的值为"obj1);Integer obj2100;System.out.println("obj2的值为"obj2);Integer obj3new Integer("-789"…

php 安装rabtmq amqp 扩展

php 安装 rabbitmq-c-0.9.0 扩展 安装 ibrabbitmq-c github 仓库地址https://github.com/alanxz/rab... 安装过程如果报错 [ 87%] Built target amqp-get Scanning dependencies of target amqp-publish [ 88%] Building C object tools/CMakeFiles/amqp-publish.dir/publis…

linux 调用rest接口,REST调用

1. 概述与SOAP相比&#xff0c;REST WebService简化了调用&#xff0c;也降低了技能要求。REST 近年来已经成为最主要的 Web 服务设计模式。 事实上&#xff0c;REST 对 Web 的影响非常大&#xff0c;由于其使用相当方便&#xff0c;已经普遍地取代了基于 SOAP 和 WSDL 的接口设…

关于JWT(Json Web Token)的思考及使用心得

什么是JWT&#xff1f; JWT(Json Web Token)是一个开放的数据交换验证标准rfc7519(php 后端实现JWT认证方法一般用来做轻量级的API鉴权。由于许多API接口设计是遵循无状态的(比如Restful)&#xff0c;所以JWT是Cookie Session这一套机制的替代方案。 组成 JWT由三部分组成头部(…

java学习(86):Interage方法compareto,parseint,intvalue

public class test22 {public static void main(String[] args){int num5;Integer obj1new Integer(num);System.out.println("obj1的值为"obj1);Integer obj2100;System.out.println("obj2的值为"obj2);Integer obj3new Integer("-789");System…

西北民族大学c语言程序设计复试科目,2016年西北民族大学中国民族信息技术研究院962C语言程序设计复试笔试仿真模拟题...

一、选择题1&#xff0e; 有如下程序&#xff1a;程序运行后的输出结果是( )。答:D【解析】程序执行过程为:定义结构体变量将ABC , 故D 项正确。2&#xff0e; 有以下程序第 2 页&#xff0c;共 33 页 调用strcpy函数为结构体成员赋值最后输出结果为赋值给程序运行后的输出结果…

JAVA四则运算(读写文件)

完成时间&#xff1a;17&#xff1a;10 package 四则运算试题;import java.io.BufferedReader; import java.io.PrintStream; import java.util.Scanner; import java.io.FileReader; import java.io.IOException; public class jisuanti {public static void main(String[] ar…

java学习(87):Interage包装类进制转换

public class test22 {public static void main(String[] args){int num5;Integer obj1new Integer(num);System.out.println("obj1的值为"obj1);Integer obj2100;System.out.println("obj2的值为"obj2);Integer obj3new Integer("-789");System…

并行DA实验c语言程序,哈工大C语言DA实验报告.doc

哈工大C语言DA实验报告哈尔滨工业大学(威海)软件学院C程序设计 实验报告编号&#xff1a;姓名院系软件学院学号任课教师指导教师于水实验地点实验时间实验名称1、国王应该给大臣多少麦子&#xff1b;2用英文字母组成一个菱形&#xff1b;3、输出一段DNA序列对应的mRNA及转录出的…