-1

我需要每隔 10 秒重复一次 Toast。我怎么能做这件事。

下面我添加一个简单的服务类代码:

public class MyService extends Service {

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    Toast.makeText(this, "Repeat After 10 Sec", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}

@Override
public void onStart(Intent intent, int startid) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
4

1 回答 1

1

今天我使用 CountDownTimer 和 Service 完成了这项工作

这是示例代码。

在役

MyTimer timer;
@Override
public void onCreate() {
   Toast.makeText(this, "Repeat After 10 Sec", Toast.LENGTH_LONG).show();
   timer = new MyTimer(200000, 10000);
}

倒计时类

class MyTimer extends CountDownTimer {

    // constructor for timer class
    public MyTimer(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);

    }

    // this method called when timer is finished
    @Override
    public void onFinish() {

        timer.start();
    }

    // this method is called for every iteration of time interval
    @Override
    public void onTick(long millisUntilFinished) {
        //display toast here
        Toast.makeText(context, "YOUR MESSAGE", Toast.LENGTH_LONG).show();
    }
   }
于 2013-09-07T10:44:50.987 回答