0

I am attempting to receive data on a phone over Bluetooth, and I am using Android Studio to attempt this. The problem is, when I run a process that listens for incoming data, I believe that the program stops at the process and waits, not allowing the rest of the program to run. I believe this because I programmed Toast to display "Data listened for" right after the method is called, yet nothing happens even if data is sent. I apologize in advance if the question seems basic, this is my first app. I think I read somewhere that beginListenForData() will need to be run on another tread to stop this exact problem, is that it? How do I go about doing that?

Here is the mainActivity code:

package com.example.root.test2;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.*;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private final int REQUEST_ENABLE_BT = 1;
    private UUID MY_UUID = UUID.fromString("d095b825-4e33-42e8-a7d0-b22fee285386");
    ListView pairedDevicesW;
    String info;
    String info_MAC;
    String info_Name;
    private BluetoothSocket BTS;
    private BluetoothDevice BTD;
    private BluetoothAdapter BTA = BluetoothAdapter.getDefaultAdapter();
    Button B_Disconnect;
    Button B_Send_Data;
    boolean is_Receiving = true;
    InputStream inStream;
    volatile boolean stopWorker;
    int readBufferPosition;
    int counter;
    byte[] readBuffer;
    Thread workerThread;
    String finalData;

    void beginListenForData() {
        final Handler handler = new Handler();
        final byte delimiter = 10;

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {
                while (!Thread.currentThread().isInterrupted() && !stopWorker)
                {
                    try {
                        int bytesAvailable = inStream.available();
                        if (bytesAvailable > 0) {
                            byte[] packetBytes = new byte[bytesAvailable];
                            inStream.read(packetBytes);
                            for (int i = 0; i < bytesAvailable; i++) {
                                byte b = packetBytes[i];
                                if (b == delimiter) {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            finalData = data;
                                        }
                                    });
                                }
                                else {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    } catch (IOException e) {
                        Log.d("TAG", e.toString());
                        stopWorker = true;
                    } catch (NullPointerException z) {
                        Log.d("TAG", z.toString());
                        stopWorker = true;
                    }
                }
            }
        });

        workerThread.start();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> pairedDevicesA= new ArrayList<String>();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pairedDevicesA);
        pairedDevicesW = (ListView)findViewById(R.id.PDL);
        B_Disconnect = (Button)findViewById(R.id.B_Disconnect);
        B_Send_Data = (Button)findViewById(R.id.B_Send_Data);

        if (BTA == null) {
            Toast.makeText(getApplication().getBaseContext(), "Bluetooth not supported", Toast.LENGTH_SHORT).show();
        }

        if (!BTA.isEnabled()) {
            Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
        }

        final Set<BluetoothDevice> pairedDevices = BTA.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice BTDevice : pairedDevices) {
                pairedDevicesA.add(BTDevice.getAddress() + "\n" + BTDevice.getName());
            }
        }
        pairedDevicesW.setAdapter(adapter);

        pairedDevicesW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                info = ((TextView)view).getText().toString();
                info_MAC = info.substring(0, 17);
                info_Name = info.substring(18);

                Toast.makeText(getBaseContext(), "Onclicklistenerstarted", Toast.LENGTH_SHORT).show();

                for (BluetoothDevice BTDevice : pairedDevices) {
                    if (BTDevice.getAddress().equals(info_MAC)) {
                        BTD = BTDevice;
                    }
                }

                Toast.makeText(getBaseContext(), "BTD set", Toast.LENGTH_SHORT).show();

                BluetoothSocket temp = null;
                try {
                    temp = BTD.createRfcommSocketToServiceRecord(MY_UUID);
                } catch (IOException e) {
                    Log.d("CONNECTTHREAD", "Could not create socket; " + e.toString());
                } catch (NullPointerException z) {
                    Log.d("CONNECTTREAD", z.toString());
                }
                BTS = temp;

                Toast.makeText(getBaseContext(), "Socket set", Toast.LENGTH_SHORT).show();

                if (BTS != null) {
                    Toast.makeText(getBaseContext(), "Socket not null", Toast.LENGTH_SHORT).show();
                    try {
                        BTS.connect();
                        Toast.makeText(getBaseContext(), "Connection Finally Fucking Made", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        Log.d("CONNECTTHREAD", "Could not connect; " + e.toString());
                        try {
                            BTS.close();
                            Toast.makeText(getBaseContext(), "Connection prematurely closed", Toast.LENGTH_SHORT).show();
                        } catch (IOException close) {
                            Log.d("CONNECTTHREAD", "Could not close connection; " + close.toString());
                        }
                    }
                    Toast.makeText(getBaseContext(), "Loop complete", Toast.LENGTH_SHORT).show();
                }
            }
        });



        InputStream tmpIn = null;
        try {
            tmpIn = BTS.getInputStream();
        } catch (IOException e) {
            Log.d("INPUTSTREAM", e.toString());
        } catch (NullPointerException z) {
            Log.d("NPE", z.toString());
        }
        inStream = tmpIn;
        Toast.makeText(getBaseContext(), "Input Stream Made", Toast.LENGTH_SHORT).show();

        while (is_Receiving) {

            beginListenForData();

            Toast.makeText(getBaseContext(), "Data listened for", Toast.LENGTH_SHORT).show();

            if (finalData != "") {
                Toast.makeText(getBaseContext(), "Data not null", Toast.LENGTH_SHORT).show();
                try {
                    Toast.makeText(getBaseContext(), finalData.toString(), Toast.LENGTH_SHORT).show();
                } catch (NullPointerException e) {
                }
            } else {
                Toast.makeText(getBaseContext(), "No Data", Toast.LENGTH_SHORT).show();
            }

            B_Disconnect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        BTS.close();
                        Toast.makeText(getBaseContext(), "Connection Closed", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {}
                    is_Receiving = false;
                }
            });
            is_Receiving = false;
        }
    }
}
PapaSulaj
  • 3
  • 2

1 Answers1

0

I think you Should instead thinking of using AsyncTask to perform background operations. Link: http://developer.android.com/reference/android/os/AsyncTask.html

Atef Hares
  • 4,715
  • 3
  • 29
  • 61