Need to repeat toast after every 10 sec using Serv

2019-06-14 22:20发布

I need to repeat Toast after every 10 second. How can I do this thing.

Below I add a simple code of the Service Class :

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();
}

1条回答
贪生不怕死
2楼-- · 2019-06-14 22:54

Today I have done this using CountDownTimer and Service

here is sample code.

In service

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

countdowntimer class

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();
    }
   }
查看更多
登录 后发表回答