简体   繁体   中英

Android: App freezes when using handler and switch

I want to repeat function every 500 milliseconds while switch is on. But when i run my code, everything freezes when i set switch on. Here is my code:

    mySwitch.setChecked(false);
    mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                pom = true;
                while (pom) {
                    final Handler h = new Handler();
                    final int delay = 1000;

                    h.postDelayed(new Runnable(){
                        public void run(){
                            myClient.SendData("AA");
                            h.postDelayed(this, delay);
                        }
                    }, delay);
                }
            }
            else{
                pom = false;
            }
        }
    });

I have tried this too, now my app doesnt freeze, now it crashes down:

    mySwitch.setChecked(false);
    mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                pom = true;
                while (pom) {
                    int delay = 0; // delay for 0 sec.
                    int period = 500; // repeat every 10 sec.
                    Timer timer = new Timer();
                    timer.scheduleAtFixedRate(new TimerTask()
                    {
                        public void run()
                        {
                            myClient.SendData("AA");
                        }
                    }, delay, period);
                }
            }
            else{
                pom = false;
            }
        }
    });

Problem is you are stuck in an infinite loop here.

while (pom) {
                final Handler h = new Handler();
                final int delay = 1000;

                h.postDelayed(new Runnable(){
                    public void run(){
                        myClient.SendData("AA");
                        h.postDelayed(this, delay);
                    }
                }, delay);
            }

The program is not able to get out of this loop because the pom is always true. And it stops responding.

This will solve your problem:
Save the state of switch in sharedPreferences and post the Runnable anywhere in activity. Send Data only when the value in sharedPreferences is true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM