[英]handler or timer android
我试着每1分钟显示一次消息! 不停! 我发现在固定延迟后只显示一次msg的例子! 你能帮忙怎么设置它? 或者如果使用计时器是更好的工作方式,我需要一个例子!
public class TimertestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
public void run() {
afficher();
}
}, 1000L);
}
public void afficher()
{
Toast.makeText(getBaseContext(),
"test",
Toast.LENGTH_SHORT).show();
}
}
谢谢!
试试这个代码 -
public class TimertestActivity extends Activity {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
afficher();
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
runnable.run();
}
public void afficher()
{
Toast.makeText(getBaseContext(),
"test",
Toast.LENGTH_SHORT).show();
handler.postDelayed(runnable, 1000);
}
}
// Timer using Handler
private final int SPLASH_TIME = 3000;
// Handling splash timer.
private void startSplashTimer() {
new Handler().postDelayed(
new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
}
}, SPLASH_TIME);
}
您可以使用TimerTask
。但是当您的设备进入休眠状态时它将无法工作,所以我认为您可以使用AlarmManager
。 无论如何,请参阅此链接以获取TimerTask
,
AlarmManager代码,
AlarmManager am = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), interval, pendingIntent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.