我想创建一个小型的android应用程序,它会在点击一个按钮(即设置活动)之后定期显示系统时间...创建按钮和设置周期的代码通过意图活动是这样的:在android中执行周期性任务
package com.example.timeupdate;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
TextView show;
@Override
protected void onCreate(Bundle I_Love_Biriyani) {
super.onCreate(I_Love_Biriyani);
setContentView(R.layout.activity_main);
button = (Button) findViewById (R.id.pressButton);
show = (TextView) findViewById (R.id.Show);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent openTimeUpdater = new Intent("com.example.timeupdate.TIMEUPDATER");
startActivity(openTimeUpdater);
}
});
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
@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;
}
}
这里是代码重复我曾经的TimerTask类来执行这项工作的计时器(比如说为5秒):
package com.example.timeupdate;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TimeUpdater extends Activity {
TextView Show;
TimerTask timer= new TimerTask(){
@Override
public void run() {
// TODO Auto-generated method stub
Date d = new Date();
Show.setText(""+d);
}
};
@Override
protected void onCreate(Bundle hotovaga) throws IllegalStateException {
// TODO Auto-generated method stub
super.onCreate(hotovaga);
setContentView(R.layout.new_update);
Show = (TextView) findViewById (R.id.time);
Timer t = new Timer();
t.scheduleAtFixedRate(timer , 0 , 5000);
}
}
点击按钮后,时间只显示一次,然后应用程序停止显示对话消息。需要解释以同样的方式完成这项工作。
你试图达到什么样的任务。你可以使用计时器或处理程序。顺便说一句,你有第二个活动中的两个计时器对象 – Raghunandan