handler thread
package com.example.handlerdemo;import java.util.Date;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Handler handler;
Button start,end;
TextView tv;
Runnable r;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)this.findViewById(R.id.textView1);
start=(Button)this.findViewById(R.id.start);
end=(Button)this.findViewById(R.id.end);
handler=new Handler();
r = new Runnable(){
@Override
public void run(){
tv.setText(new Date().toString());
handler.postDelayed(r, 1000);
}
};
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v){
handler.post(r);
}
});
end.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
handler.removeCallbacks(r);
}
});
}
@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;
}
}
文档来源:51CTO技术博客https://blog.51cto.com/u_15322177/3266602
页:
[1]