'How to run app in backgorund amdroid studio/java

I want my app to write to my bluetooth receiver commend until i hold a button, then the commend will change and continue when i release. (it will send 0 always until i will hold, and then it will send 1 and when i release 0 again). I tried to make a thread it will send the 0 that is working but when i hold the button it sends 1(as intened) but when i release it doesnt sends 0 again.

package com.example.bluetooth;
import static android.text.TextUtils.concat;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
    private OutputStream outputStream;
    Spinner spinner;
    ArrayList<String> deviceName = new ArrayList<String>();
    Map<String, String> devicesDict = new HashMap<String, String>();
    Object[] devices;
    EditText InputTI;
    Button sendB;
    Button commend1B;
    String message;
    Boolean connected = false;
    Boolean sending = false;
    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
        if (blueAdapter != null) {
            if (blueAdapter.isEnabled()) {
                Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

                if(bondedDevices.size() > 0) {

                    devices = (Object []) bondedDevices.toArray();
                    Log.i("devices:","devices[0]"+devices[0]);
                    Log.i("devices:","devices[1]"+devices[1]);
                    Log.i("devices:","devices[2]"+devices[2]);
                    BluetoothDevice result = null;
                    for (BluetoothDevice device : bondedDevices) {
                        devicesDict.put(""+device.getName(), ""+device);
                    }
                    Log.i("dict","dict"+devicesDict);

                    deviceName.add("Select:");
                    for(Map.Entry<String,String> entry : devicesDict.entrySet()){
                        deviceName.add(entry.getKey()+";"+entry.getValue());
                    }

                    spinner = (Spinner) findViewById(R.id.ListSp);
                    ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, deviceName);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner.setAdapter(adapter);

                }

                Log.e("error", "No appropriate paired devices.");
            } else {
                Log.e("error", "Bluetooth is disabled.");
            }
        }

        InputTI = findViewById(R.id.InputTI);
        sendB = findViewById(R.id.sendB);
        commend1B = findViewById(R.id.commend1B);
        Thread thread = new Thread(runnable);
        commend1B.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                sending = true;
                try {
                    Log.i("sending","sending 1");
                    write("1#");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                sending = false;
                return false;
            }

        });




        sendB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("sendState","state"+sending);
                message = InputTI.getText().toString()+"#";
                try {
                    write(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String[] splitted;
                splitted = adapterView.getSelectedItem().toString().split(";");
                if (blueAdapter != null) {
                    if (blueAdapter.isEnabled()) {
                        if (!adapterView.getSelectedItem().toString().equals("Select:")) {
                            for (Object o : devices) {
                                if (o.toString().equals(splitted[1])) {
                                    connected = true;
                                    BluetoothDevice device = (BluetoothDevice) o;
                                    ParcelUuid[] uuids = device.getUuids();

                                    BluetoothSocket socket = null;
                                    try {
                                        socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    try {

                                        socket.connect();
                                    } catch (IOException e) {
                                        Log.e("ConnectFail", "Socket.connect() Failed", e);
                                        //e.printStackTrace();

                                        break;
                                    }
                                    try {
                                        outputStream = socket.getOutputStream();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                    if (connected && !sending) {
                                        Log.i("sending", "sending 021");
                                        thread.start();
                                    }
                                }
                            }
                        }else{
                            connected = false;
                        }
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        }
    Runnable runnable = new Runnable(){
        public void run() {
            while (connected && !sending) {
                    try {

                        Log.i("sending", "sending 0");
                        write("0#");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
    };




    public void write(String s) throws IOException {
        outputStream.write(s.getBytes());
    }


Solution 1:[1]

To run background services you need to use Service class or/and Background Threads.

Service documentation: https://developer.android.com/guide/components/services

BackGround Threads: https://developer.android.com/guide/background/threading

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michele Verriello