无法建立蓝牙连接和应用崩溃

时间:2018-05-28 22:06:43

标签: android android-studio bluetooth android-bluetooth

我正在试图弄清楚如何设置蓝牙连接,但我的应用程序一直在崩溃。

我认为我在acceptConnect的实施方面有些不妥之处,但我无法弄清楚它是什么。这是我正在使用的代码:

public class Menu extends AppCompatActivity {

    private BluetoothAdapter BTAdapter;
    public static int REQUEST_BLUETOOTH = 1;
    private BluetoothSocket bTSocket;
    private BluetoothServerSocket mmServerSocket;
    InputStream mmInputStream;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    int counter;
    volatile boolean stopWorker;

    static ArrayList<String> people = new ArrayList<String>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);

        //Set socket to initially null
        bTSocket = null;

        //Enable bluetooth
        BTAdapter = BluetoothAdapter.getDefaultAdapter();
        // Phone does not support  Bluetooth so let the user know and exit.
        if (BTAdapter == null) {
            new AlertDialog.Builder(this)
                    .setTitle("Not compatible")
                    .setMessage("Your phone does not support Bluetooth")
                    .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            System.exit(0);
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }

        //Request enabling
        if (!BTAdapter.isEnabled()) {
            Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBT, REQUEST_BLUETOOTH);
        }

        acceptConnect(BTAdapter);
        beginListenForData();


        // ArrayList<String> people = new ArrayList<String>();


        final ListView mylv = (ListView) findViewById(R.id.mylv);

        ArrayAdapter<String> adapter =
                new ArrayAdapter<String>(getApplicationContext(),
                        android.R.layout.simple_list_item_1,
                        people) {

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {

                        View view = super.getView(position, convertView, parent);
                        TextView text = (TextView) view.findViewById(android.R.id.text1);

                        Attendee a1 = new Attendee("Taylor", "Taylor LN");
                        Attendee a2 = new Attendee("Emily", "Emily LN");
                        Attendee a3 = new Attendee("Mark", "Mark LN");
                        Attendee a4 = new Attendee("Steve", "Steve LN");

                        // String[] here = {a1.getfName(), a2.getfName(), a3.getfName(), a4.getfName()};
                        ArrayList<String> here = new ArrayList<String>();
                        here.add(a1.getfName());
                        here.add(a2.getfName());
                        here.add(a3.getfName());
                        here.add(a4.getfName());

                        String person = String.valueOf(mylv.getItemAtPosition(position));


                        if (here.contains(person) ){
                            text.setTextColor(Color.rgb(0,153,76));

                        }else{
                            text.setTextColor(Color.RED);

                        }

                        mylv.setOnItemClickListener(
                                new AdapterView.OnItemClickListener(){
                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                        //String[] here = {"Steve", "Taylor", "Emily", "Mark"};
                                        ArrayList<String> here = new ArrayList<String>();
                                        here.add("Steve");
                                        here.add("Taylor");
                                        here.add("Emily");
                                        here.add("Mark");

                                        String person = String.valueOf(parent.getItemAtPosition(position));
                                        if (Arrays.asList(here).contains(person)
                                                ){
                                            Toast.makeText(Menu.this, person + " is here", Toast.LENGTH_LONG).show();
                                        }
                                        else
                                        {
                                            //  Toast.makeText(Menu.this, person + " is not here", Toast.LENGTH_LONG).show();

                                        }


                                    }
                                }
                        );

                        return view;
                    }
                };

        mylv.setAdapter(adapter);
        mylv.setVisibility(View.GONE);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    public void back(View view)
    {
        Intent intent = new Intent(Menu.this, List.class);

        closeConnect();

        startActivity(intent);

    }

    void acceptConnect(BluetoothAdapter bTAdapter) {
        BluetoothServerSocket temp = null;
        Log.d("SERVERCONNECT", "Attempting to create server");
        UUID mUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
        try {
            //temp = bTAdapter.listenUsingRfcommWithServiceRecord(bTAdapter.getName(), mUUID);
            //Testing with hard coded name
            temp = bTAdapter.listenUsingInsecureRfcommWithServiceRecord("Attend", mUUID);
        }
        catch(IOException e) {
            Log.d("SERVERCONNECT", "Could not get a BluetoothServerSocket:" + e.toString());
        }
        //mmServerSocket = temp;
        while(true) {
            try {
                bTSocket = temp.accept();
                Log.d("SERVERCONNECT", "Changing temp to bTSocket");
            }
            catch (IOException e) {
                Log.d("SERVERCONNECT", "Could not accept an incoming connection.");
                break;
            }
            if (bTSocket != null) {

                try {
                    Log.d("SERVERCONNECT", "Closing temp");
                    temp.close();
                }
                catch (IOException e) {
                    Log.d("SERVERCONNECT", "Could not close ServerSocket:" + e.toString());
                }
                break;
            }
        }
    }

    public void closeConnect() {
        stopWorker = true;
        try {
            mmInputStream.close();
        } catch(IOException e){
            Log.d("SERVERCONNECT", "Could not close connection:" + e.toString());
        }
        try {
            bTSocket.close();
        } catch(IOException e) {
            Log.d("SERVERCONNECT", "Could not close connection:" + e.toString());
        }
    }

    void beginListenForData()
    {
        final Handler handler = new Handler();
        final byte delimiter = 10; //This is the ASCII code for a newline character

        try {
            mmInputStream = bTSocket.getInputStream();
        } catch(IOException e){
            Log.d("LISTEN", "Could not create input stream" + e.toString());
        }
        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {
                while(!Thread.currentThread().isInterrupted() && !stopWorker)
                {
                    try
                    {
                        int bytesAvailable = mmInputStream.available();
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.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()
                                    {
                                        public void run()
                                        {
                                            people.add(data);
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        stopWorker = true;
                    }
                }
            }
        });

        workerThread.start();
    }

}

任何帮助将不胜感激..谢谢

1 个答案:

答案 0 :(得分:0)

请检查createMessage()中的acceptConnect()方法是否被视为无视蓝牙可用性。

onCreate()

只有在蓝牙可用时才能继续。

您可以处理用户选择正常或拒绝蓝牙时发生的情况

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

    //Set socket to initially null
    bTSocket = null;

    //Enable bluetooth
    BTAdapter = BluetoothAdapter.getDefaultAdapter();
    // Phone does not support  Bluetooth so let the user know and exit.
    if (BTAdapter == null) {
        new AlertDialog.Builder(this)
                .setTitle("Not compatible")
                .setMessage("Your phone does not support Bluetooth")
                .setPositiveButton("Exit", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        System.exit(0);
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    //Request enabling
    if (!BTAdapter.isEnabled()) {
        Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBT, REQUEST_BLUETOOTH);
    }
    // wait until the request is accepted, and then continue
    else
    {
        acceptConnect(BTAdapter);
        beginListenForData();
    }
}