[英]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.