Android的:在一个Intent服务停止处理程序在一定的时间在一、时间、程序、Android

2023-09-03 22:32:32 作者:可能是你喜欢优秀而我姓梁

我有一个启动处理程序的intentService,但一定时间后,我需要停止处理程序。我不知道如何做到这一点。我有下面的类,但我只是不知道如何停止,一旦时间达到了处理程序,或者当一定量的小时/分钟通过。我想这是尽可能提高效率,请。

I have an intentService that starts a handler, but after a certain amount of time I need to stop the handler. I'm not sure how to do this. I have the class below, but I'm just not sure how to stop the handler once the time is reached, or when a certain amount of hours/min passes. I would like this to be as efficient as possible please.

公共类RedirectService扩展IntentService {

public class RedirectService extends IntentService {

private Handler handler;
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        foobar();
        handler.postDelayed(this, 2000);
    }
};

public LockedRedirectService() {
    super("RedirectService");
}

@Override
protected void onHandleIntent(Intent redirectIntent) {
    // Gets data from the incoming Intent
   int hour = redirectIntent.getIntExtra("hour", 0);
    int min = redirectIntent.getIntExtra("minute", 0);



    handler.postDelayed(runnable, 2000);
    handler.removeCallbacks(runnable);
}

}

推荐答案

开始一个新的线程和等待。当时间到,停止和删除可运行。 或者用处理后的另一个延迟可运行,停止和删除工作可运行。

Start a new thread and wait. When time's up, stop and remove the runnable. Or use handler to post another delayed runnable to stop and remove the working runnable.

    public class RedirectService extends IntentService {

    private Handler handler;
    private boolean mRun = false;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (mRun) {
                foobar();
                handler.postDelayed(this, 2000);
            }
        }
    };

    public LockedRedirectService() {
        super("RedirectService");
    }

    @Override
    protected void onHandleIntent(Intent redirectIntent) {
        // Gets data from the incoming Intent
        final int hour = redirectIntent.getIntExtra("hour", 0);
        final int min = redirectIntent.getIntExtra("minute", 0);


        mRun = true;
        handler.postDelayed(runnable, 2000);
        //handler.removeCallbacks(runnable);

        new Thread(new Runnable() {
            @Override
            public void run() {
                Thread.currentThread();
                try {
                    Thread.sleep((hour * 60 + min) * 60 * 1000);
                } catch (Exception ignore) {}
                mRun = false;
                handler.removeCallbacks(runnable);
           }
        }).start();

        /* or use handler
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRun = false;
                handler.removeCallbacks(runnable);
           }
        }, (hour * 60 + min) * 60 * 1000);
        */
    }

    }