我正在开发一个应用程序,我想在其中实现计时器任务,每5秒打一次Toast消息。问题是我的应用程序在运行它5秒后崩溃.Below是我的代码的一部分,请告诉我我在哪里犯错误,如何克服它。
public class main_activity extends Activity implements BluetoothLeUart.Callback{
public ImageButton fabbutton;
Activity activity;
Timer time;
TimerTask timetask;
Handler handle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
fabbutton = (ImageButton) findViewById(R.id.fabbutton);
startTimer(); //this is where I start my timer task
fabbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scanLeDevice(false);
Intent intent = new Intent(getApplicationContext(), ScanList.class);
startActivity(intent);
}
});
}
public void startTimer(){
time = new Timer();
initializeTimerTask();
time.schedule(timetask, 5000, 10000);
}
public void initializeTimerTask(){
timetask = new TimerTask() {
@Override
public void run() {
handle.post(new Runnable() {
@Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (time != null) {
time.cancel();
time = null;
}
}
}
答案 0 :(得分:1)
你忘了初始化处理程序,
只需在oncreate
或startTimer();
handle = new Handler();
甚至在您的情况下,您可以使用,
runOnUiThread(new Runnable(){
@Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});