现在的位置: 首页 > 综合 > 正文

使用任务管理器完成文本的自动更新

2018年03月31日 ⁄ 综合 ⁄ 共 1847字 ⁄ 字号 评论关闭
文章目录

 

消息机制

线程间的通讯

  在Android中,主线程称为UI线程,一个界面显示,那么着就属于主线程;

而子线程指的是那些利用Runnable实现的线程操作类。

  子线程不能更新主线程中的各个组件的状态,即,只要是子线程就无法更新组件。

所以子线程要操作信息,就要在主线程中利用Handler处理这些信息,从而实现线程的操作。

 

 

在main.xml中:

 

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical"

    android:background="#000000">

  <TextView

      android:id="@+id/info"

      android:layout_marginTop="8dp"

      android:gravity="center_horizontal"

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:textSize="30dp"

      android:textColor="#ffffff"/>

 

</LinearLayout>

 

 

 

 

 

 

在MyMessageDemo.java中:

 

package com.li.messageproject;

 

import java.util.Timer;

import java.util.TimerTask;

 

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.TextView;

import android.support.v4.app.NavUtils;

 

public class MyMessageDemo extends Activity {

  private TextView info = null;

  private static int count = 0;    //表示更新后的记录

  private static final int SET = 1;  //操作的what状态

  private Handler myHandler = new Handler(){

     @Override

     public void handleMessage(Message msg) {

       switch(msg.what){    //判断操作的信息类型

       case SET:       //更新组件

         MyMessageDemo.this.info.setText("更新数据:  " + count++);

       }

     }

  };

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        super.setContentView(R.layout.main);

        this.info = (TextView)super.findViewById(R.id.info);

        Timer timer = new Timer();

        timer.schedule(new MyTask(),0,1000);  //启动定时调度

    }

    private class MyTask extends TimerTask{    //定时调度类

     public void run() {

       Message msg = new Message();  //设置更新

       msg.what = SET;    //操作的标记

       MyMessageDemo.this.myHandler.sendMessage(msg); //发送信息

      

     }   

    }

}

 

抱歉!评论已关闭.