title: how to run infinite loop in background android
body: <p>I have a client in android connected to a server in c++ using TCP sockets.
  I need my app to constantly send an image to the server. I tried using an infinite(while) loop, but then my app does not do anything else while running the loop, and I need my app to constantly send the image but also be able to run tasks at the same time.
  this is my code:</p>
  
  <pre><code>    class sendImage implements Runnable{
      @Override
      public void run() {
          while(true){
                try {
                      Bitmap bmp=screenShot();
                      ByteArrayOutputStream bosBitmap = new ByteArrayOutputStream(); 
                      bmp.compress(CompressFormat.JPEG, 50, bosBitmap); 
                      byte[] arrayBitmap = bosBitmap.toByteArray();   
  
                      OutputStream os = socket.getOutputStream();
                      BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
                      DataOutputStream dos = new DataOutputStream(bos);
                      dos = new DataOutputStream(os);
                      dos.write(arrayBitmap, 0, arrayBitmap.length);
                      dos.flush();
                      memecontentView.destroyDrawingCache();  
              } catch (UnknownHostException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }       
      }
  }
  </code></pre>
  
  <p>and when I click a button this is how I initialize the thread</p>
  
  <pre><code>public void onClick(View view) {
      new Thread(new sendImage()).start();
  }
  </code></pre>
  
  <p>But when I click the button, the image is sent but it does not allow me to do anything else, if I press another button, my app closes
  How can I run an infinite loop that allows my app to perform other tasks at the same time?</p>