当前位置: 移动技术网 > 移动技术>移动开发>Android > Android Timer使用的实例代码

Android Timer使用的实例代码

2019年07月24日  | 移动技术网移动技术  | 我要评论

1:服务端使用php

复制代码 代码如下:

<?php
    echo date('y-m-d h:i:s');
?>

2:activity_main.xml

复制代码 代码如下:

<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">

    <button
        android:id="@+id/btn_click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button start"/>

    <textview
        android:id="@+id/tv_show"
        android:layout_below="@id/btn_click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:textsize="28sp"/>

    <button
        android:id="@+id/btn_stop"
        android:layout_below="@id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button stop"/>

</relativelayout>

3:mainactivity.java

httphelper.getstringfromnet2(param)此方法见:

复制代码 代码如下:

public class mainactivity extends activity {
    private button btnclick=null;
    private button btnstop=null;
    private textview tvshow=null;
    private string info="";
    private timer timer=null;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);

        btnclick=(button)findviewbyid(r.id.btn_click);
        btnstop=(button)findviewbyid(r.id.btn_stop);
        tvshow=(textview)findviewbyid(r.id.tv_show);

        timer=new timer();

        btnclick.setonclicklistener(new onclicklistener(){
            public void onclick(view view){
                timer.scheduleatfixedrate(new mytask(), 100, 2000);
            }
        });

        btnstop.setonclicklistener(new onclicklistener(){
            public void onclick(view view){
                timer.cancel();
            }
        });

    }
   

    handler myhandler=new handler(){
        public void handlemessage(message msg){
            if(info!=""){
                tvshow.settext(info);
            }
        }
    };

    private class mytask extends timertask{
        public void run(){
            string param="http://192.168.0.116/android/time.php";
            info=httphelper.getstringfromnet2(param);
            myhandler.obtainmessage(100).sendtotarget();
        }
    }
}

4:运行结果:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网