Как остановить метод мерцания в onDestroy () Android-студии? - PullRequest
0 голосов
/ 27 марта 2019

Я хочу остановить обработчик в 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();
}

1 Ответ

0 голосов
/ 29 марта 2019

Обрабатывать логическое значение 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();
    }
}
...