Timer 和TimerTask到底怎么用?
package com.flyinbed.isme;import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MianActivity extends Activity {
public Button btn;
public Context context = this;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mian);
btn = (Button) this.findViewById(R.id.btn1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Timer t = new Timer(true);
t.schedule(new TimerTask() {
public void run() {
Toast.makeText(context, "TimerTask", Toast.LENGTH_LONG).show();
System.out.print("Isme");
}
}, 1000, 5000);
}
});
}
}
不报错,运行就报错!
创建TimerTask对象,覆盖Run方法,
创建Timer对象,添加schedule运行务务?
流程不对吗? Timer TimerTask --------------------编程问答-------------------- public Context context = this; 这个应该写在
setContentView(R.layout.mian);下面,试试。
--------------------编程问答-------------------- 子线程没有Looper,显示Toast会报错,可以用handler来做。
package com.flyinbed.isme;
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.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MianActivity extends Activity {
public Button btn;
public Context context = this;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Toast.makeText(context, "TimerTask", Toast.LENGTH_LONG).show();
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) this.findViewById(R.id.btn1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
// Toast.makeText(context, "TimerTask", Toast.LENGTH_LONG).show();
handler.sendEmptyMessage(0);
System.out.print("Isme");
}
}, 1000, 5000);
}
});
}
}
补充:移动开发 , Android