Android studio java thread doesn't work properly

232 views Asked by At

I have a switch button in my android application. I make a thread which work is randomly flashing. I put a Start method when switch button is on and interrupt the method when the button is off. It works the first time but the second time when I touch the switch button the application ends automatically. I press the button then the random flashing work then I stop the button and the flashing stops but when I start it again with the button the app stops by itself.

xx=new Runnable()
    {
        @Override
        public void run()
        {
            synchronized (this)
            {
                while (true)
                {
                    try {


                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                        camera.setParameters(parameters);
                        camera.stopPreview();

                        c1.sleep(100);
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                        camera.setParameters(parameters);
                        camera.startPreview();
                        //c1.interrupt();


                    }
                    catch (Exception e)
                    {
                        Thread.currentThread().interrupt();
                        break; //this is a MUST

                    }

                }
            }
            }
        //}

    };


    c1 =new Thread(xx);

   s1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (s1.isChecked())

            {
                c1.start();
            }
            else
            {
                c1.interrupt();

            }

        }

    });
1

There are 1 answers

2
ahmed shaaban On

why you need to use synchronized when u use it it block the resource so no one will use it again until it release by listeners u can keep synchronized but at least stop instead of true in while use flag and when button off make it false :)

// set this to true to stop the thread
  volatile boolean shutdown = false;

also u need to use in catch to stop thread so not make it stop app :)

catch (InterruptedException e) {
              // good practice
              Thread.currentThread().interrupt();
              return;
      }