通过已建立的蓝牙连接发送/写入

时间:2014-10-01 15:46:34

标签: android bluetooth

我正在创建一个Android应用程序,其中我有几个彩色按钮,当点击时通过蓝牙将一些文本发送到嵌入式蓝牙模块。

我能够成功连接到配对设备(带蓝牙无线电的pcb),但是当我尝试发送数据时,我得到一个空指针异常(如下所示),我是新手,并不明白什么是ive如果可以的话,请查看代码并协助我。

这是代码:

package sjtech.rompa.wifi;

    public class Wifi extends Activity implements OnItemClickListener {

        ArrayAdapter<String> listAdapter;
        ListView listView;
        BluetoothAdapter btAdapter;
        Set<BluetoothDevice> devicesArray;
        ArrayList<String> pairedDevices;
        ArrayList<BluetoothDevice> devices;
        public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        protected static final int SUCCESS_CONNECT = 0;
        protected static final int MESSAGE_READ = 1;
        IntentFilter filter;
        BroadcastReceiver receiver;
        String tag = "debugging";


        private Button currentcolour;
        private Button redbtn; 
        private Button grnbtn;
        private Button bluebtn; 
        private Button yellowbtn;
        private Button orangebtn; 
        private Button purplebtn;
        private Button pinkbtn; 
        private Button whitebtn;
        private Button resetbtn;
        private Button blueleftarrow; 
        public BluetoothDevice mBluetoothAdapter;
        public String outputStream;          
        public InputStream inStream;
        public ImageView btoff;
        MediaPlayer sndred;
        MediaPlayer sndgrn;
        MediaPlayer sndblue;
        MediaPlayer sndyel;
        MediaPlayer sndwht;
        MediaPlayer sndpnk;
        MediaPlayer sndpple;
        MediaPlayer sndorng;
        MediaPlayer sndrst;

Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                Log.i(tag, "in handler");
                super.handleMessage(msg);
                switch(msg.what){
                case SUCCESS_CONNECT:
                    // DO something
       ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
                    Toast toast= Toast.makeText(getApplicationContext(),     
                              "CONNECT", Toast.LENGTH_SHORT);  
                              toast.setGravity(Gravity.CENTER, 0, 0);
                              toast.show();
                    String s = "successfully connected";
                    connectedThread.write(s.getBytes());
                    Log.i(tag, "connected");
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[])msg.obj;
                    String string = new String(readBuf);
    Toast toast2= Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT);
                    toast2.setGravity(Gravity.CENTER, 0, 0);
                    toast2.show();

                    break;

                }
            }
        };
        @Override
        public void onCreate(Bundle savedInstanceState) {                                                                                       
super.onCreate(savedInstanceState);




                  currentcolour= (Button) findViewById(R.id.currentcolour);                   

            init();
            if(btAdapter==null){                                                    //if no BT then show toast and close.                 Toast toast3= Toast.makeText(getApplicationContext(), "No bluetooth detected", Toast.LENGTH_SHORT);
            toast3.setGravity(Gravity.CENTER, 0, 0);
            toast3.show();


                finish();
            }
            else{
                if(!btAdapter.isEnabled()){                                             //if BT available but not enabled turn on BT.
                    turnOnBT();
                }

                getPairedDevices();
                startDiscovery();
            }

         //**********************************************RED BUTTON***********  ***************************************
            sndred = MediaPlayer.create(Wifi.this, R.raw.sndred); // create instance of mediaPlayer
            redbtn = (Button) findViewById(R.id.redbtn);     // Get a reference to the button
            redbtn.setOnClickListener(new View.OnClickListener() {   // Set the click listener to run the code.
            @Override
            public void onClick(View v) {                       // red button's click event 

            sndred.start();                                // play red sound                
            currentcolour.setBackgroundColor(Color.RED);                                    //set currentColour to red. 

            ConnectedThread con = new ConnectedThread(null);           

            con.write("".getBytes());                    //Send string via bluetooth.                                        
        //  con.write(new byte[] {0x30, 0x38,});         //Send byte via bluetooth.

            }
            });

    }   
            });  





        }
        private void startDiscovery() {
            // TODO Auto-generated method stub
            btAdapter.cancelDiscovery();
            btAdapter.startDiscovery();

        }
        private void turnOnBT() {
            // TODO Auto-generated method stub
            Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
        }
        private void getPairedDevices() {
            // TODO Auto-generated method stub
            devicesArray = btAdapter.getBondedDevices();
            if(devicesArray.size()>0){
                for(BluetoothDevice device:devicesArray){
                    pairedDevices.add(device.getName());

                }
            }
        }
        private void init() {
            // TODO Auto-generated method stub
            listView=(ListView)findViewById(R.id.listView);
            listView.setOnItemClickListener(this);
            listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
            listView.setAdapter(listAdapter);
            btAdapter = BluetoothAdapter.getDefaultAdapter();
            pairedDevices = new ArrayList<String>();
            filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            devices = new ArrayList<BluetoothDevice>();
            receiver = new BroadcastReceiver(){
                @Override
                public void onReceive(Context context, Intent intent) {
                    // TODO Auto-generated method stub
                    String action = intent.getAction();

                    if(BluetoothDevice.ACTION_FOUND.equals(action)){
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        devices.add(device);
                        String s = "";
                        for(int a = 0; a < pairedDevices.size(); a++){
                            if(device.getName().equals(pairedDevices.get(a))){
                                //append 
                                s = "(Paired)";
                                break;
                            }
                        }

                        listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
                    }

                    else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                         Toast toast= Toast.makeText(getApplicationContext(),   //Show toast that bluetooth is already disabled. 
                                  "STARTED DEVICE DISCOVERY", Toast.LENGTH_SHORT);  
                                  toast.setGravity(Gravity.CENTER, 0, 0);
                                  toast.show();
                    }
                    else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                         Toast toast= Toast.makeText(getApplicationContext(),   //Show toast that bluetooth is already disabled. 
                                  "FINISHED DEVICE DISCOVERY!", Toast.LENGTH_SHORT);  
                                  toast.setGravity(Gravity.CENTER, 0, 0);
                                  toast.show();



                    }
                    else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                        if(btAdapter.getState() == btAdapter.STATE_OFF){
                            turnOnBT();
                        }
                    }

                }
            };

            registerReceiver(receiver, filter);
             filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            registerReceiver(receiver, filter);
             filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            registerReceiver(receiver, filter);
             filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(receiver, filter);
        }


        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            unregisterReceiver(receiver);
        }

            @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                // TODO Auto-generated method stub
                super.onActivityResult(requestCode, resultCode, data);
                if(resultCode == RESULT_CANCELED){
       Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue",  Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,   //when discovered item in listview is selected then: cancel discovery, start connection
                    long arg3) {
                // TODO Auto-generated method stub

                if(btAdapter.isDiscovering()){
                    btAdapter.cancelDiscovery();
                }
                if(listAdapter.getItem(arg2).contains("Paired")){

                    BluetoothDevice selectedDevice = devices.get(arg2);
                    ConnectThread connect = new ConnectThread(selectedDevice);
                    connect.start();
                    Log.i(tag, "in click listener");
                }
                else{
          Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
                }
            }

            private class ConnectThread extends Thread {

                private final BluetoothSocket mmSocket;
                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;
                    Log.i(tag, "construct");
                    // 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);
                    } catch (IOException e) { 
                        Log.i(tag, "get socket failed");

                    }
                    mmSocket = tmp;
                }

                public void run() {
                    // Cancel discovery because it will slow down the connection
                    btAdapter.cancelDiscovery();
                    Log.i(tag, "connect - run");
                    try {
                        // Connect the device through the socket. This will block
                        // until it succeeds or throws an exception
                        mmSocket.connect();
                        Log.i(tag, "connect - succeeded");

             } catch (IOException connectException) {    Log.i(tag, "connect failed");
                        // 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)

                    mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
                }



                /** 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 mmSocket;
                private final InputStream mmInStream;
                private final OutputStream mmOutStream;

                public ConnectedThread(BluetoothSocket socket) {
                    mmSocket = socket;
                    InputStream tmpIn = null;
                    OutputStream tmpOut = null;

                    // Get the input and output streams, using temp objects because
                    // member streams are final
                    try {
Null pointer points here>>>>  tmpIn = socket.getInputStream(); <<<<*******************
                      tmpOut = socket.getOutputStream();
                    } catch (IOException e) { }

                    mmInStream = tmpIn;
                    mmOutStream = tmpOut;


                }

                public void run() {
                    byte[] buffer;  // buffer store for the stream
                    int bytes; // bytes returned from read()

                    // Keep listening to the InputStream until an exception occurs
                    while (true) {
                        try {
                            // Read from the InputStream
                            buffer = new byte[1024];
                            bytes = mmInStream.read(buffer);
                            // Send the obtained bytes to the UI activity
                            mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                                    .sendToTarget();

                        } catch (IOException e) {
                            break;
                        }
                    }
                }

                /* Call this from the main activity to send data to the remote device */
                public void write(byte[] bytes) {
                    try {
                        mmOutStream.write(bytes);
                    } catch (IOException e) { 
                        e.printStackTrace();

                    }
                }

                /* Call this from the main activity to shutdown the connection */
                public void cancel() {
                    try {
                        mmSocket.close();
                    } catch (IOException e) { }
                }
            }

我在logcat中得到的空指针异常指向ConnectedThread中的以下行:

            tmpIn = socket.getInputStream();

我这样调用write():

    ConnectedThread con = new ConnectedThread(null);    //Create an instance of ConnectedThread 

    con.write("ABC".getBytes());                            //Send string via bluetooth.                                         
//  con.write(new byte[] {0x30, 0x38,});                //Send byte via bluetooth.

以下是logcat中的行:

10-02 08:02:44.539: E/AndroidRuntime(23489): FATAL EXCEPTION: main
10-02 08:02:44.539: E/AndroidRuntime(23489): java.lang.NullPointerException
10-02 08:02:44.539: E/AndroidRuntime(23489): at sjtech.rompa.wifi.Wifi$ConnectedThread.<init>(Wifi.java:491)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at sjtech.rompa.wifi.Wifi$2.onClick(Wifi.java:158)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at android.view.View.performClick(View.java:4452)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at android.widget.Button.performClick(Button.java:148)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at android.view.View$PerformClick.run(View.java:18428)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at android.os.Handler.handleCallback(Handler.java:725)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at android.os.Looper.loop(Looper.java:176)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at android.app.ActivityThread.main(ActivityThread.java:5365)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at java.lang.reflect.Method.invokeNative(Native Method)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at java.lang.reflect.Method.invoke(Method.java:511)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
10-02 08:02:44.539: E/AndroidRuntime(23489):    at dalvik.system.NativeStart.main(Native Method)

非常感谢提前帮助!! 尼尔

1 个答案:

答案 0 :(得分:0)

问题在于此代码:

ConnectedThread con = new ConnectedThread(null);

您正在使用null实例化ConnectedThread类。因此,参数“socket”接收null:

public ConnectedThread(BluetoothSocket socket) {

因此空指针:

tmpIn = socket.getInputStream();

基本上错误与蓝牙无关。