无法在Android上使用蓝牙发送数据

时间:2015-11-20 07:17:07

标签: android bluetooth connectivity

我使用connectthread方法在android中创建了一个用于从蓝牙进行数据传输的应用程序,但遗憾的是它不起作用。当选择列表中的蓝牙设备时,应用程序不做任何工作。以下是我的主要源代码。请指导我哪里出错。

public class MainActivity extends AppCompatActivity {

    private OutputStream ostream;
    private InputStream istream;
    public static final int RECIEVE_MESSAGE = 2;
    ListView listViewPaired;
    ListView listViewDetected;
    ArrayList<String> arrayListpaired;
    Button buttonSearch, buttonOn, buttonDesc, buttonOff;
    ArrayAdapter<String> adapter, detectedAdapter, mNewDevicesArrayAdapter;
    static HandleSeacrh handleSeacrh;

    BluetoothDevice bdDevice;
    BluetoothClass bdClass;
    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
    private ButtonClicked clicked;
    ListItemClickedonPaired listItemClickedonPaired;
    BluetoothAdapter bluetoothAdapter = null;
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
    ListItemClicked listItemClicked;
    UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         //ConnectedThread mConnectedThread;

        listViewDetected = (ListView) findViewById(R.id.listViewDetected);
        listViewPaired = (ListView) findViewById(R.id.listViewPaired);
        buttonSearch = (Button) findViewById(R.id.buttonSearch);
        buttonOn = (Button) findViewById(R.id.buttonOn);
        buttonDesc = (Button) findViewById(R.id.buttonDesc);
        buttonOff = (Button) findViewById(R.id.buttonOff);
        arrayListpaired = new ArrayList<String>();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        clicked = new ButtonClicked();
        handleSeacrh = new HandleSeacrh();
        arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
        /*
         * the above declaration is just for getting the paired bluetooth devices;
         * this helps in the removing the bond between paired devices.
         */
        listItemClickedonPaired = new ListItemClickedonPaired();
        arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
        adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayListpaired);
        detectedAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_single_choice);
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_single_choice);
        listViewDetected.setAdapter(detectedAdapter);
        listItemClicked = new ListItemClicked();
        detectedAdapter.notifyDataSetChanged();
        listViewPaired.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        getPairedDevices();
        buttonOn.setOnClickListener(clicked);
        buttonSearch.setOnClickListener(clicked);
        buttonDesc.setOnClickListener(clicked);
        buttonOff.setOnClickListener(clicked);
        listViewDetected.setOnItemClickListener(listItemClicked);
        listViewPaired.setOnItemClickListener(listItemClickedonPaired);
    }

    private void getPairedDevices() {
        Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
        if (pairedDevice.size() > 0) {
            for (BluetoothDevice device : pairedDevice) {
                arrayListpaired.add(device.getName() + "\n" + device.getAddress());
                arrayListPairedBluetoothDevices.add(device);
            }
        }
        adapter.notifyDataSetChanged();
    }

    class ListItemClicked implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            bdDevice = arrayListBluetoothDevices.get(position);
            //bdClass = arrayListBluetoothDevices.get(position);
            Log.i("Log", "The dvice : " + bdDevice.toString());
            /*
             * here below we can do pairing without calling the callthread(), we can directly call the
             * connect(). but for the safer side we must usethe threading object.
             */
            //callThread();
            //connect(bdDevice);
            Boolean isBonded = false;
            try {
                isBonded = createBond(bdDevice);
                if (isBonded) {
                    //arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
                    //adapter.notifyDataSetChanged();
                    Log.i("Log", "Paired");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }//connect(bdDevice);
            Log.i("Log", "The bond is created: " + isBonded);
     //        btSend();

            try
            {
                BluetoothSocket socket=bdDevice.createRfcommSocketToServiceRecord(applicationUUID);
                socket.connect();
                ConnectedThread mConnectedThread = new ConnectedThread(socket);
                mConnectedThread.start();
                mConnectedThread.write("Hi");
                mConnectedThread.run();

            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

  /*  public void btSend()
    {


        String path = Environment.getExternalStorageDirectory()+"/hi.txt";

        File file = new File(path);

        BluetoothSocket socket= null;
        try {
            socket = bdDevice.createRfcommSocketToServiceRecord(applicationUUID);
            socket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
       Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        startActivity(intent);
      /* ContentValues values = new ContentValues();
        values.put(BluetoothShare.URI, path);
        values.put(BluetoothShare.DESTINATION,bdDevice.getAddress());
        values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
        Long ts = System.currentTimeMillis();
        values.put(BluetoothShare.TIMESTAMP, ts);
        getContentResolver().insert(BluetoothShare.CONTENT_URI,values);}*/


    class ListItemClickedonPaired implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            bdDevice = arrayListPairedBluetoothDevices.get(position);
            try {
                Boolean removeBond = removeBond(bdDevice);
                if (removeBond) {
                    arrayListpaired.remove(position);
                    adapter.notifyDataSetChanged();
                }


                Log.i("Log", "Removed" + removeBond);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /*private void callThread() {
        new Thread(){
            public void run() {
                Boolean isBonded = false;
                try {
                    isBonded = createBond(bdDevice);
                    if(isBonded)
                    {
                        arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
                        adapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }//connect(bdDevice);
                Log.i("Log", "The bond is created: "+isBonded);
            }
        }.start();
    }*/
    private Boolean connect(BluetoothDevice bdDevice) {
        Boolean bool = false;
        try {
            Log.i("Log", "service method is called ");
            Class cl = Class.forName("android.bluetooth.BluetoothDevice");
            Class[] par = {};
            Method method = cl.getMethod("createBond", par);
            Object[] args = {};
            bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
            //Log.i("Log", "This is: "+bool.booleanValue());
            //Log.i("Log", "devicesss: "+bdDevice.getName());
        } catch (Exception e) {
            Log.i("Log", "Inside catch of serviceFromDevice Method");
            e.printStackTrace();
        }
        return bool.booleanValue();
    }

    ;


    public boolean removeBond(BluetoothDevice btDevice)
            throws Exception {
        Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
        Method removeBond = btClass.getMethod("removeBond");
        Boolean returnValue = (Boolean)removeBond.invoke(btDevice);
        return returnValue.booleanValue();
    }


    public boolean createBond(BluetoothDevice btDevice)
            throws Exception {
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
        return returnValue.booleanValue();
    }


    class ButtonClicked implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.buttonOn:
                    onBluetooth();
                    break;
                case R.id.buttonSearch:
                    arrayListBluetoothDevices.clear();
                    startSearching();
                    break;
                case R.id.buttonDesc:
                    makeDiscoverable();
                    break;
                case R.id.buttonOff:
                    offBluetooth();
                    break;
                default:
                    break;
            }
        }
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Message msg = Message.obtain();
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
                Toast.makeText(getApplicationContext(), "Searching for devices", Toast.LENGTH_LONG).show();
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                try {
                    //device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
                    //device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
                } catch (Exception e) {
                    Log.i("Log", "Inside the exception: ");
                    e.printStackTrace();
                }

                if (arrayListBluetoothDevices.size() < 1) // this checks if the size of bluetooth device is 0,then add the
                {                                           // device to the arraylist.
                    detectedAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                    detectedAdapter.notifyDataSetChanged();
                } else {
                    boolean flag = true;    // flag to indicate that particular device is already in the arlist or not
                    for (int i = 0; i < arrayListBluetoothDevices.size(); i++) {
                        if (device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress())) {
                            flag = false;
                        }
                    }
                    if (flag == true) {
                        detectedAdapter.add(device.getName() + "\n" + device.getAddress());
                        arrayListBluetoothDevices.add(device);
                        detectedAdapter.notifyDataSetChanged();
                    }
                }
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

                //ParcelUuid[] uuids= device.getUuids();
              /*  try
                {
                    BluetoothSocket socket=device.createRfcommSocketToServiceRecord(applicationUUID);
                    socket.connect();
                    ConnectedThread mConnectedThread = new ConnectedThread(socket);
                    mConnectedThread.start();
                    mConnectedThread.write("Hi");

                } catch (IOException e) {
                    e.printStackTrace();
                }
*/




            }
        }
    };

    private void startSearching() {
        Log.i("Log", "in the start searching method");
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        MainActivity.this.registerReceiver(myReceiver, intentFilter);
        bluetoothAdapter.startDiscovery();
    }

    private void onBluetooth() {
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
            Log.i("Log", "Bluetooth is Enabled");
            Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
        }
    }

    private void offBluetooth() {
        if (bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.disable();
            Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_LONG).show();
        }
    }

   private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

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

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

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[256];  // 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
                    bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                } catch (IOException e) {
                    break;
                }
            }
        }

          //Call this from the main activity to send data to the remote device
        public void write(String message) {
            Log.i("TAG", "...Data to send: " + message + "...");
            byte[] msgBuffer = message.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Log.i("TAG", "...Error data send: " + e.getMessage() + "...");
            }
        }
    }


    private void makeDiscoverable() {
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);
        Log.i("Log", "Discoverable ");
    }

    class HandleSeacrh extends Handler
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case 111:

                    break;

                default:
                    break;
            }
        }
    }

    Handler h =new Handler()
    {
        public void handleMeassage(Message msg)
        {
            byte[] writeBuf = (byte[]) msg.obj;
            int begin = (int)msg.arg1;
            int end = (int)msg.arg2;

            switch(msg.what) {
                case 1:
                    String writeMessage = new String(writeBuf);
                    writeMessage = writeMessage.substring(begin, end);
                    break;
            }
        }
    };


}

这是Log:

11-20 16:07:58.125 222-660/? D/audio_hw_primary: select_devices: done
11-20 16:07:58.135 12248-12248/com.example.toshiba.bluetoothdemo D/AndroidRuntime: Shutting down VM
11-20 16:07:58.135 12248-12248/com.example.toshiba.bluetoothdemo W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41648d58)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime: FATAL EXCEPTION: main
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime: Process: com.example.toshiba.bluetoothdemo, PID: 12248
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at java.util.ArrayList.get(ArrayList.java:308)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at com.example.toshiba.bluetoothdemo.MainActivity$ListItemClicked.onItemClick(MainActivity.java:125)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.widget.AdapterView.performItemClick(AdapterView.java:299)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.widget.AbsListView.performItemClick(AbsListView.java:1115)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2928)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.widget.AbsListView$3.run(AbsListView.java:3691)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:733)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:136)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5113)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:515)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
11-20 16:07:58.145 12248-12248/com.example.toshiba.bluetoothdemo E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
11-20 16:07:58.155 1670-2285/? I/KLO_Stability: [am_crash][1448015878]:[12248,0,com.example.toshiba.bluetoothdemo,13155910,java.lang.IndexOutOfBoundsException,Invalid index 3, size is 3,ArrayList.java,255]
11-20 16:07:58.165 1195-1390/? I/WhetstoneService: Receive am_crash event for pid: 12248
11-20 16:07:58.165 1195-1390/? W/KloServer: Aborted broadcast does not supprt for: com.example.toshiba.bluetoothdemo
11-20 16:07:58.185 942-1450/? W/ActivityManager:   Force finishing activity com.example.toshiba.bluetoothdemo/.MainActivity
11-20 16:07:58.195 1670-2285/? I/libmc: received event[index:0,mask:0x80,name:data_app_crash@1448015878194.txt]
11-20 16:07:58.195 1670-2285/? I/KLO_Stability: get wanted event[mask:128, name:data_app_crash@1448015878194.txt] from the watchset
11-20 16:07:58.195 1670-2285/? I/KLO_Stability: start gathering logcat log...
11-20 16:07:58.195 1670-2285/? I/KLO_Stability: gathering logcat log done
11-20 16:07:58.315 1195-1390/? I/libmc: group sys_app_bg memory.limit_in_bytes is set to -1
11-20 16:07:58.315 1195-1390/? I/libmc: group sys_app_bg memory.soft_limit_in_bytes is set to -1
11-20 16:07:58.315 942-956/? I/ActivityManager: Start proc com.qualcomm.logkit for broadcast com.qualcomm.logkit/.autotrigger.AutotriggerReceiver: pid=24531 uid=10045 gids={50045, 1028, 1015, 1023, 1007, 3003, 3002}
11-20 16:07:58.455 1195-1390/? I/libmc: task pid 24531 have been add to group sys_app_bg.
11-20 16:07:58.455 1195-1390/? I/libmc: [sys_app_bg]cgroup_add_tasks max single write time: 133ms
11-20 16:07:58.455 1195-1390/? I/libmc: [sys_app_bg]cgroup_add_tasks total time consume: 133ms
11-20 16:07:58.455 1195-24535/? E/libmc: set memory.limit_in_bytes[-2] failed: Invalid argument
11-20 16:07:58.475 1222-1929/? I/RenderThread: RenderThread resumed
11-20 16:07:58.475 1222-1929/? I/RenderThread: All controllers paused.
11-20 16:07:58.475 1222-1929/? I/RenderThread: RenderThread paused, waiting for signal
11-20 16:07:58.485 942-956/? V/LocationPolicy: onForegroundActivitiesChanged
11-20 16:07:58.495 24531-24531/? D/ActivityThread: handleBindApplication:com.qualcomm.logkit
11-20 16:07:58.505 24531-24531/? D/ActivityThread: setTargetHeapUtilization:0.75
11-20 16:07:58.505 24531-24531/? D/ActivityThread: setTargetHeapMinFree:2097152
11-20 16:07:58.585 24531-24531/? D/MainApp: [onCreate] 
11-20 16:07:58.585 24531-24531/? D/MainApp: [init] 
11-20 16:07:58.585 24531-24531/? D/UtilsSettings: [updateCurProfilePreference] 
11-20 16:07:58.585 24531-24549/? D/ProfileDBManager: [openDataBase] 
11-20 16:07:58.585 24531-24549/? D/ProfileDBManager: [access$000] DataBaseManagementHelper
11-20 16:07:58.595 24531-24531/? D/MainApp: [getExternalAndInternalStoragePath] external sdcard-> /storage/sdcard1
11-20 16:07:58.595 24531-24531/? D/AutotriggerReceiver: [onReceive]  Intent { act=android.intent.action.DROPBOX_ENTRY_ADDED flg=0x10 cmp=com.qualcomm.logkit/.autotrigger.AutotriggerReceiver (has extras) }
11-20 16:07:58.595 24531-24531/? D/AutotriggerReceiver: [onReceive] android.intent.action.DROPBOX_ENTRY_ADDED: data_app_crash
11-20 16:07:58.615 24531-24549/? D/ProfileDBManager: [fetchProfile] 
11-20 16:07:58.625 24531-24549/? D/ProfileDBManager: [closeDataBase] 
11-20 16:07:58.655 942-1282/? I/ActivityManager: Killing 13578:com.miui.cloudservice/u0a30 (adj 15): empty for 693s
11-20 16:07:58.695 942-956/? W/ActivityManager: Activity pause timeout for ActivityRecord{43038228 u0 com.example.toshiba.bluetoothdemo/.MainActivity t6 f}
11-20 16:07:58.705 1369-1578/? D/PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.miui.home/com.miui.home.launcher.Launcher}
11-20 16:07:58.705 1222-1929/? I/RenderThread: RenderThread resumed
11-20 16:07:58.705 1222-1929/? I/RenderThread: All controllers paused.
11-20 16:07:58.705 1222-1929/? I/RenderThread: RenderThread paused, waiting for signal
11-20 16:07:58.725 942-956/? I/Timeline: Timeline: App_transition_ready time:2197056
11-20 16:07:58.735 1222-1222/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@42472848 time:2197064
11-20 16:07:58.915 942-955/? I/Timeline: Timeline: Activity_windows_visible id: ActivityRecord{42e08e00 u0 com.miui.home/.launcher.Launcher t1} time:2197241
11-20 16:07:58.925 942-955/? I/Timeline: Timeline: App_transition_stopped time:2197252
11-20 16:07:58.925 942-956/? V/LocationPolicy: onForegroundActivitiesChanged
11-20 16:07:59.125 222-222/? I/AudioFlinger: setAppName(), name=[system_server], active=[0]
11-20 16:08:01.275 222-969/? D/audio_hw_primary: out_standby: enter: stream (0xb81cbea8) usecase(1: low-latency-playback)
11-20 16:08:01.445 222-969/? I/listen_hal_loader: audio_extn_listen_update_stream_status(): uc_id 1 of type 0 for Event 2, with Raise=0
11-20 16:08:01.445 222-969/? D/hardware_info: hw_info_append_hw_type : device_name = speaker
11-20 16:08:01.465 222-969/? I/listen_hal_loader: audio_extn_listen_update_device_status(): device 0x2 of type 0 for Event 0, with Raise=0
11-20 16:08:01.705 1195-1195/? W/WhetstoneService: do not trim { PackageName :com.example.toshiba.bluetoothdemo Pid: 12248 Uid: 0 Start by: activity Score:50 Old score:50 state:0 mBackgroundTimeInMillis:1448015878198 WakelockCount:0 wakelogsize:0  ActivityDestroied:false Activity size: 0 PackageInfo:{WhetstonePackageInfo#PacakgeName:com.example.toshiba.bluetoothdemoFlag:5312 [,TRIMHEAPS,SOFT_RESET,ZRAM,FLAG_DEAL_SCHEDULE] Type:0[] } tasknum:13}
11-20 16:08:02.205 12328-24074/? I/BluetoothAdapterProperties: Callback:discoveryStateChangeCallback with state:0 disc: true
11-20 16:08:02.205 12024-12024/? V/BluetoothDiscoveryReceiver: Received: android.bluetooth.adapter.action.DISCOVERY_FINISHED
11-20 16:08:02.315 24609-24609/? W/: [ColorAdjust] gammamode=2, cemode=10
11-20 16:08:02.315 24609-24609/? W/: [ColorAdjust] temp_gammavalue=2, temp_cevalue=10
11-20 16:08:02.315 24609-24609/? W/: [ColorAdjust] Don't setGamma!
11-20 16:08:02.315 24609-24609/? W/: [ColorAdjust] Don't setCe!
11-20 16:08:02.315 24609-24609/? W/: [ColorAdjust] Set temp_prefer temp_ce!

1 个答案:

答案 0 :(得分:0)

这可能是问题

您已将RECIEVE_MESSAGE值设置为2

public static final int RECIEVE_MESSAGE = 2;

然后当你从inputstream接收数据并使用RECIEVE_MESSAGE arg在处理程序中发送它

       bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
       h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();

但在你处理程序中,你只需在开关盒中使用1,实际应该是2() 所以正确的代码应该是

switch(msg.what) {
                case RECIEVE_MESSAGE: // value is 2 here now
                    String writeMessage = new String(writeBuf);
                    writeMessage = writeMessage.substring(begin, end);
                    break;
            }

测试它,如果其他东西工作正常,你可能会得到一条消息