Android Studio - 问题与设备连接导致套接字关闭

时间:2018-05-25 16:26:58

标签: java android sockets android-studio bluetooth

我正在尝试创建一个连接到蓝牙设备的Android应用程序,并且正在努力连接。当我尝试连接时运行run()方法它不起作用并转到代码的catch部分给我"套接字关闭"的输出。我不确定为什么尝试不起作用。  我知道我的代码有几个缺陷,我在Android开发的第5天,但是我能得到的任何帮助都将非常感激。我需要解决的一个大问题是能够连接到设备并最终能够从中接收数据流。

     public class BluetoothConnection extends Thread {

        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        byte[] buffer;
        BluetoothAdapter mmAdapter;


        // Unique UUID for this application, you may use different
        private static final UUID MY_UUID = UUID
                .fromString("eb58f747-a241-4ccb-935d-04ac6039895d");



        public BluetoothConnection(BluetoothDevice device) {

            BluetoothSocket tmp = null;
            mmAdapter = null;
            System.out.println("\n\n\n\n\n\n print is working? \n\n\n\n\n\n");

            // Get a BluetoothSocket for a connection with the given BluetoothDevice
            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmSocket = tmp;

            //now make the socket connection in separate thread to avoid FC
            Thread connectionThread  = new Thread(new Runnable() {

                @Override
                public void run() {
                    // Always cancel discovery because it will slow down a connection
                    Log.d("workkkkkk","$$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$");

                    //mmAdapter.cancelDiscovery();


                }
            });

            connectionThread.start();

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    mmSocket.connect();


                    System.out.println("\n\n\n\n\n\n socket connected\n\n\n\n\n\n");

                } catch (IOException e) {
                    //connection to device failed so close the socket
                    try {
                        mmSocket.close();
                        System.out.println("\n\n\n\n\n\n socket closed\n\n\n\n\n\n");

                    } catch (IOException e2) {
                        System.out.println("\n\n\n\n\n\n in catch\n\n\n\n\n\n");

                        e2.printStackTrace();
                    }
                }

                tmpIn = mmSocket.getInputStream();
                tmpOut = mmSocket.getOutputStream();
                buffer = new byte[1024];
            } catch (IOException e) {
                e.printStackTrace();
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }


        public void run() {

            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    //read the data from socket stream
                    if(mmInStream != null) {
                        mmInStream.read(buffer);

                    }
                    // Send the obtained bytes to the UI Activity
                } catch (IOException e) {
                    //an exception here marks connection loss
                    //send message to UI Activity
                    break;
                }
            }
        }

        public void write(byte[] buffer) {
            try {
                //write the data to socket stream
                if(mmOutStream != null)
                mmOutStream.write(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }

这是在我的DeviceList类中运行的。我在这里遇到了多个问题,但最重要的是与BluetoothConnection.java有关但是我不确定问题是否因为这个类而发生。

package com.example.curie.fairbanks_01;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;

import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;

import android.util.Log;
import android.view.View;
import android.view.MenuItem;

import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Switch;
import android.widget.Toast;
import android.content.Intent;


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

public class DeviceList extends Activity {

    Button deviceSearch;
    Switch btSwitch;


    private BluetoothAdapter BA;
    private Set<BluetoothDevice>pairedDevices;
    private String instrumentName;
    private UUID instrumentUUID;
    BluetoothSocket socket;
    BluetoothConnection connector;

    ListView lv;
    public static BluetoothDevice instrument;
    PopupMenu pMenu;
    ArrayList<MenuItem> popupList;
    ArrayList<BluetoothDevice> list;

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

        deviceSearch = (Button) findViewById(R.id.device_search);
        deviceSearch.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(DeviceList.this, findViewById(R.id.device_search));
                pairedDevices = BA.getBondedDevices();

                list = new ArrayList<BluetoothDevice>();
                for (BluetoothDevice bt : pairedDevices) {

                    list.add(bt);
                    popup.getMenu().add(bt.getName());
                    popup.show();
                }

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {


                        ArrayList<BluetoothDevice> deviceArrayList = new ArrayList<BluetoothDevice>(pairedDevices);

                        Toast.makeText(DeviceList.this, "Testing: " + item.getTitle(), Toast.LENGTH_SHORT).show();

                       // instrument = deviceArrayList.get(deviceArrayList.indexOf(item.getItemId()));
                        instrument = deviceArrayList.get(0);

                        connector = new BluetoothConnection(instrument);
                        connector.run();
                        Toast.makeText(DeviceList.this, "Connected to : " + item.getTitle(), Toast.LENGTH_SHORT).show();
                        Intent myIntent = new Intent(DeviceList.this, InputActivity.class);
                        DeviceList.this.startActivity(myIntent);
                        return true;
                    }
                });

            }
                });


         btSwitch = (Switch) findViewById(R.id.switch1);

        BA =BluetoothAdapter.getDefaultAdapter();
        lv =(ListView) findViewById(R.id.listView);

        if(BA.isEnabled())
            btSwitch.setChecked(true);
        else
            btSwitch.setChecked(false);
//        pMenu = new PopupMenu(this,findViewById(R.id.device_search));

        }



    public void list(View v){
//        pairedDevices = BA.getBondedDevices();
//
//        ArrayList list = new ArrayList();
//
//        for(BluetoothDevice bt : pairedDevices){
//
//            list.add(bt.getName());
//            pMenu.getMenu().add(bt.toString());
//        }

        Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();

        final ArrayAdapter adapter = new  ArrayAdapter(this,android.R.layout.simple_list_item_1, list);

        lv.setAdapter(adapter);
    }


    public void onOff(View v)
    {
        if(BA.isEnabled())
        {
                BA.disable();
                Toast.makeText(getApplicationContext(), " BT Turned off" ,Toast.LENGTH_LONG).show();
        }
        else
        {             BA.enable();
             Toast.makeText(getApplicationContext(), "BT Turned on" ,Toast.LENGTH_LONG).show();
        }
    }

    public static BluetoothDevice getInstrument() {
        return instrument;
    }
}

当我选择要连接的设备时,这是在控制台上运行的内容:

I/System.out: $$$$$$$$$$$$$$$$****** in constructor ******$$$$$$$$$$$$$$$$
        D/workkkkkk: $$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$
        D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
        D/BluetoothSocket: connect(): myUserId = 0
        W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
        I/System.out: $$$$$$$$$$$$$$$$****** socket closed ******$$$$$$$$$$$$$$$$
        D/BluetoothSocket: getInputStream(): myUserId = 0
        getOutputStream(): myUserId = 0

为什么不在试用中连接?

0 个答案:

没有答案