如何在onDestroy()android Studio中停止blink方法?

问题描述 投票:0回答:1

我想在onDestroy()中停止处理程序。代码如下。 blink()方法因活动中的特殊原因而调用,但希望将其服务停止在destroy方法中。

final Handler handler = new Handler();
private void blink() {
    PrintLog.log("On", "Blink Thread");
    new Thread(new Runnable() {
        @Override
        public void run() {
            int timeToBlink = 1000;    //in milissegunds
            try {
                Thread.sleep(timeToBlink);
            } catch (Exception e) {
            }
            handler.post(new Runnable() {
                @Override
                public void run() {

                    if (text_ATMCardInstruction.getVisibility() == View.VISIBLE) {
                        text_ATMCardInstruction.setVisibility(View.INVISIBLE);
                    } else {
                        text_ATMCardInstruction.setVisibility(View.VISIBLE);
                    }
                    blink();
                }
            });
        }
    }).start();
}

@Override
protected void onDestroy() {

    // what is code here?
    PrintLog.log("Stop", "serviceStop");
    super.onDestroy();
}
java android handler runnable
1个回答
0
投票

处理treadRunning布尔值onDestroy()方法set treadRunning = false;

private void blink() {
    PrintLog.log("On", "Blink Thread");

    if (treadRunning) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                int timeToBlink = 1000;    //in milissegunds
                try {
                    Thread.sleep(timeToBlink);
                } catch (Exception e) {
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (text_ATMCardInstruction.getVisibility() == View.VISIBLE) {
                            text_ATMCardInstruction.setVisibility(View.INVISIBLE);
                        } else {
                            text_ATMCardInstruction.setVisibility(View.VISIBLE);
                        }
                        blink();
                    }
                });
            }
        }).start();
    } else {
        PrintLog.log("On", "Blink Thread Stop");
        new Thread(new Runnable() {
            @Override
            public void run() {
                text_ATMCardInstruction.setVisibility(View.INVISIBLE);
            }
        }).interrupt();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.