Android / Java BluetoothSocket InputStream不会读取数据

时间:2015-07-26 17:53:46

标签: android sockets bluetooth

我正在实现一个简单的应用程序,通过蓝牙在两个设备之间发送和接收数据。 我正在关注Android开发者博客的蓝牙聊天示例,但我的应用程序似乎无法从套接字的输入流中读取。

写入套接字很好。该应用程序不会抛出错误,也不会更新textview。任何帮助,将不胜感激。谢谢!

主要activity.java(显示和选择设备列表) - 可能不是错误文件:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

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


public class MainActivity extends ActionBarActivity {
    private final static int REQUEST_ENABLE_BT = 22;
    private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    private static final String NAME = "Bluetooth!";
    ListView listView;
    ArrayList<BluetoothDevice> deviceList;
    ArrayAdapter<String> arrayAdapter;
    ScanReciever reciever;
    BluetoothAdapter bluetooth_adapter;
    Button onButton;
    Button scanButton;
    Button alreadyButton;
    AcceptThread acceptThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        deviceList = new ArrayList<>();
        //arrayAdapter = new ArrayAdapter<>(this, R.xml.table_item, android.R.id.text1, deviceList);
        arrayAdapter = new ArrayAdapter<String>(this, R.layout.table_item);

        // Set up Buttons
        onButton = (Button) findViewById(R.id.onButton);
        scanButton = (Button) findViewById(R.id.scanButton);
        onButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                askAdapterOn();
            }
        });
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanForDevices();
            }
        });

        // Set up listview
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
                callButtons(deviceList.get(position));
            }
        });

        // Bluetooth setup.
        bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
        // If device is incapable of using bluetooth:
        if (bluetooth_adapter == null) {
            onButton.setEnabled(false);
            scanButton.setEnabled(false);
        }
        else if (!bluetooth_adapter.isEnabled()) { // If bluetooth is off:
            //Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            onButton.setEnabled(true);
            scanButton.setEnabled(false);
        }
        else { // Bluetooth is on and ready:
            onButton.setEnabled(false);
            scanButton.setEnabled(true);


            alreadyButton = (Button) findViewById(R.id.alreadyButton);
            alreadyButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Collect current devices into a set.
                    Set<BluetoothDevice> pairedDevices = bluetooth_adapter.getBondedDevices();
                    // Pass the index of the paired device
                    if (pairedDevices.size() > 0) {
                        callButtons(pairedDevices.iterator().next()); // First element in set.
                    } else {
                        System.out.println("No paired Device!");
                    }
                }
            });

            acceptThread = new AcceptThread();
            acceptThread.start();
        }
    }

    private class ScanReciever extends BroadcastReceiver  {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                System.out.println("Started");
                //discovery starts, we can show progress dialog or perform other tasks
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                System.out.println("finished");
                //discovery finishes, dismis progress dialog
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //bluetooth device found
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                System.out.println("FOUND: " + device.getName());
                deviceList.add(device);
                arrayAdapter.add(device.getName()+" - Click to pair");
                arrayAdapter.notifyDataSetChanged();
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                System.out.println("Connected~!!!!!!!!!!!!!!");
                callButtons(deviceList.get(deviceList.size()-1));
            }

        }
    };

    protected void askAdapterOn() {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    protected void scanForDevices() {
        IntentFilter filter = new IntentFilter();

        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        reciever = new ScanReciever();
        registerReceiver(reciever, filter);
        bluetooth_adapter.startDiscovery();
    }

    protected void callButtons(BluetoothDevice bd) {
        bluetooth_adapter.cancelDiscovery();
        Intent toButton = new Intent(getApplicationContext(), buttons.class);
        toButton.putExtra("selected",bd);
        startActivity(toButton);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK){
                if (bluetooth_adapter.isEnabled()){
                    onButton.setEnabled(false);
                    scanButton.setEnabled(true);
                }
                else {
                    onButton.setEnabled(true);
                    scanButton.setEnabled(false);
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(reciever);

        super.onDestroy();
    }

    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {
            // Use a temporary object that is later assigned to mmServerSocket,
            // because mmServerSocket is final
            BluetoothServerSocket tmp = null;
            try {
                // MY_UUID is the app's UUID string, also used by the client code
                tmp = bluetooth_adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
                System.out.println("READY TO ACCEPT");
            } catch (IOException e) { }
            mmServerSocket = tmp;
        }

        public void run() {
            BluetoothSocket socket = null;
            // Keep listening until exception occurs or a socket is returned
            while (true) {
                try {
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    break;
                }
                // If a connection was accepted
                if (socket != null) {
                    // Do work to manage the connection (in a separate thread)
                    //manageConnectedSocket(socket);
                    try {
                        mmServerSocket.close();
                    } catch (IOException e) { }
                    break;
                }
            }
        }

        /** Will cancel the listening socket, and cause the thread to finish */
        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) { }
        }
    }
}

Buttons.java(应用程序将启动连接并保持通信) - 可能是包含错误的文件:

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

public class buttons extends Activity {
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    BluetoothDevice selected;
    BluetoothAdapter bluetoothAdapter;
    TextView tv;
    Button button1;
    Button button2;
    Button button3;
    Button unpairB;
    private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    ConnectThread connectThread;
    ConnectedThread connectedThread;
    BluetoothSocket mmSocket;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buttons);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        selected = getIntent().getExtras().getParcelable("selected");
        pair(selected);
        connectedThread = null;
        try {
            connectedThread = new ConnectedThread(mmSocket);
            connectedThread.start();
            System.out.println("ConnectedThread started!");
        } catch (Exception e) {
            Log.e("unpair()", e.getMessage());
        }

        // Set up Buttons
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        unpairB = (Button) findViewById(R.id.unpairButton);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonPressed(1);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonPressed(2);
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonPressed(3);
            }
        });
        unpairB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unpair(selected);
                finish();
            }
        });

        // Set up textview
        tv = (TextView) findViewById(R.id.textView);
        tv.setText("connected to: " + selected.getName());
    }

    protected void buttonPressed(int i) {
        connectedThread.write(i);
        tv.setText(Integer.toString(i));
    }

    private void pair(BluetoothDevice device) {
        connectThread = new ConnectThread(device);
        connectThread.start();
    }

    private void unpair(BluetoothDevice device) {
        try {
            Method m = device.getClass().getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            Log.e("unpair()", e.getMessage());
        }
    }

    private class ConnectThread extends Thread {
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket,
            // because mmSocket is final
            BluetoothSocket tmp = null;
            mmDevice = device;

            // Get a BluetoothSocket to connect with the given BluetoothDevice
            try {
                // MY_UUID is the app's UUID string, also used by the server code
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                System.out.println("Socket was created in ConnectThread");
            } catch (IOException e) { }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the connection
            // bluetoothAdapter.cancelDiscovery();

            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                } catch (IOException closeException) { }
                return;
            }

            // Do work to manage the connection (in a separate thread)
            //manageConnectedSocket(mmSocket);
        }

        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket bluetoothSocket;
        private final InputStream inputStream;
        private final OutputStream outputStream;

        public ConnectedThread(BluetoothSocket socket) {
            this.bluetoothSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            System.out.println("Connected to " + socket.getRemoteDevice().getName());
            try {
                tmpIn = bluetoothSocket.getInputStream();
                tmpOut = bluetoothSocket.getOutputStream();
            } catch (IOException e) {
            }

            inputStream = tmpIn;
            outputStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            if (inputStream == null) System.out.println("Inputstream is null");
            else System.out.println("Inputstream is safe");
            if (outputStream == null) System.out.println("outstream is null");
            else System.out.println("Outputstream is safe");
            while (true) {
                try {
                    System.out.println("Blocking?");
                    bytes = inputStream.read(buffer);
                    System.out.println("NO");
                    handler.obtainMessage(MESSAGE_READ, bytes, -1,
                            buffer).sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }


        public void write(int i) {
            try {
                byte[] buffer = new byte[1024];
                buffer[0] = (byte) i;
                outputStream.write(buffer);
                outputStream.flush();
                handler.obtainMessage(MESSAGE_WRITE, -1, -1,
                        buffer).sendToTarget();
                System.out.println("Write SUCCESS!!!!!!!!!!!!!!");
            } catch (IOException e) {
                System.out.println("write ERRORRRRRRRRRRRRRRRRR");
            }
        }

        public void cancel() {
            try {
                bluetoothSocket.close();
            } catch (IOException e) {
            }
        }
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_WRITE:
                    System.out.println("Write was broadcasted");
                    byte[] writeBuf = (byte[]) msg.obj;
                    String writeMessage = new String(Integer.toString(writeBuf[0]));
                    ///tv.setText(writeMessage);
                    break;
                case MESSAGE_READ:
                    System.out.println("Read was broadcasted");
                    byte[] readBuf = (byte[]) msg.obj;
                    String readMessage = new String(Integer.toString(readBuf[0]));
                    tv.setText(readMessage);
                    break;
            }
        }
    };
}

0 个答案:

没有答案