点击Start按钮,每隔3秒在Logcat里打印一句话
<Button android:id="@+id/startButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start"/> <Button android:id="@+id/endButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/startButton" android:text="End"/>
MainActivity.java
package com.example.handler_01; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.os.Handler; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends ActionBarActivity { private Button startButton = null; private Button endButton = null; Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startButton = (Button) findViewById(R.id.startButton); endButton = (Button) findViewById(R.id.endButton); startButton.setOnClickListener(new StartButtonListener()); endButton.setOnClickListener(new EndButtonListener()); } class StartButtonListener implements OnClickListener{ @Override public void onClick(View v) { handler.post(updateThread); } } class EndButtonListener implements OnClickListener{ @Override public void onClick(View v) { handler.removeCallbacks(updateThread); } } Runnable updateThread = new Runnable() { @Override public void run() { System.out.println("updateThread"); handler.postDelayed(updateThread, 3000); } }; }
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1579277
原文地址:http://shamrock.blog.51cto.com/2079212/1579277