• android handler机制和Timer采用


    Timer主要用于创建一个任务来定期运行。

    创建继承Task该任务等级。即任务每次跑。

    private class MyTask extends TimerTask
    	{
    		@Override
    		public void run() {
    			Message msg = new Message();
    			msg.what = 1;
    			handler.sendMessage(msg);
    		}
    	}
    }
    
    之后就能够使用了

    Timer timer = new Timer();
    timer.schedule(new MyTask(), 1, 2000);

    也能够直接使用线程简历耗时操作。这里也就做一个Timer和Thread的差别使用吧。

    private class MyTread extends Thread
    {
    	int i = 0;
    	@Override
    	public void run()
    	{
    		while(true)
    		{
    			system.out.println();
    			i++:
    			try
    			{
    				sleep(1000);
    			}
    			catch(InterruptedException e)
    			{
    				e.printStackTrace();
    			}
    		}
    	}
    }



    Hanler机制:使用hanler.sendMessage(msg)传递Message參数 在新建Handler中的handleMessage( )

    方法接受參数。依据msg.what进行操作推断,进行对应的操作。

    总体代码:

    package com.example.androidtest;
    import java.util.Timer;
    import java.util.TimerTask;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.view.Menu;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
    	TextView show;
    	@SuppressLint("HandlerLeak")
    	Handler handler = new Handler()
    	{
    		@Override
    		public void handleMessage(Message msg)
    		{
    			switch(msg.what)
    			{
    			case 1:
    				show.setText("标题为:" + title);
    				title ++;
    				break;
    			}
    			super.handleMessage(msg);
    		}
    	};
    	int title = 0;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		show = (TextView)findViewById(R.id.show);
    		Timer timer = new Timer();
    		timer.schedule(new MyTask(), 1, 2000);
    	}
    	@Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    		// Inflate the menu; this adds items to the action bar if it is present.
    		getMenuInflater().inflate(R.menu.main, menu);
    		return true;
    	}
    	private class MyTask extends TimerTask
    	{
    		@Override
    		public void run() {
    			Message msg = new Message();
    			msg.what = 1;
    			handler.sendMessage(msg);
    		}
    	}
    }
    





    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    Assembly之instruction之CMP
    Assembly之Instruction之Byte and Word
    MSP430之section(1)
    MSP430之software development flow
    openMSP430之Custom linker script
    CDC之Synchronizers
    CDC之Metastability
    Embedded之Stack之三
    Embedded之Stack之二
    Embedded之Stack之一
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4823525.html
Copyright © 2020-2023  润新知