Android蓝牙在添加断点时发送msg,但如果程序没有暂停则不发送

时间:2017-02-16 03:49:19

标签: java android bluetooth

我有以下代码与计算机上的C#程序对话。当我在outputStream.write(bytes)代码之前添加断点时,它在我重新启动程序时工作正常。如果我只是让程序运行,它就不会发送消息。我认为这与时间有关,但我已经尝试了一切我能想到的,以确保BT在发送消息之前已连接。

点击按钮即发送消息。

以下是两个班级:

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static BluetoothAdapter mBluetoothAdapter;
    public static BluetoothDevice mBluetoothDevice;
    private String scannedContents;
    private Button scanBtn;
    private TextView formatTxt, contentTxt;
    public static int mState = 0;
    private ConnectThread btThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Bottom Right Buttons
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);

        //Setup BT
        if (savedInstanceState == null) {
            mBluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
            if (mBluetoothAdapter != null) {
                if (mBluetoothAdapter.isEnabled()) {
                    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                    if (pairedDevices.size() > 0) {
                        for (BluetoothDevice device : pairedDevices) {
                            if (device.getAddress().equalsIgnoreCase("00:1a:7d:da:71:11")) {
                                mBluetoothDevice = device;
                                ConnectThread btThread = new ConnectThread(mBluetoothDevice);
                                btThread.run();
                            }
                        }
                    } else
                        showErrorText(R.string.bt_not_paired);

                } else {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, Constants.REQUEST_ENABLE_BT);
                }
            } else {
                showErrorText(R.string.bt_not_supported);
            }
        }
        //Scanning Button Code
        scanBtn = (Button) findViewById(R.id.scan_button);
        formatTxt = (TextView) findViewById(R.id.scan_format);
        contentTxt = (TextView) findViewById(R.id.scan_content);
        scanBtn.setOnClickListener(this);

    }

    public void onClick(View v) {
        //respond to clicks
        if (v.getId() == R.id.scan_button) {
            //scan
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();
        } else if (v.getId() == R.id.fab) {
            btThread.write(scannedContents.getBytes());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.REQUEST_ENABLE_BT:
                if (resultCode == RESULT_OK) {
                    //TODO
                } else {
                    Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                    finish();
                }
            case Constants.REQUEST_SCANNED_DATA:
                //Scanner Code
                IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                if (scanningResult.getContents() != null) {
                    //we have a result
                    String scanContent = scanningResult.getContents();
                    String scanFormat = scanningResult.getFormatName();
                    //TODO Do something with data
                    this.scannedContents = scanContent;
                    formatTxt.setText("FORMAT: " + scanFormat);
                    contentTxt.setText("CONTENT: " + scanContent);
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_SHORT);
                    toast.show();
                }
            default:
                super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @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);
    }

    private void showErrorText(int messageId) {
        TextView view = (TextView) findViewById(R.id.error_textview);
        view.setText(getString(messageId));
    }

    public final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //TODO
        }
    };
}

ConnectThread.java

public class ConnectThread extends Thread {

    final BluetoothSocket mmSocket;

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

        try {
            // Get a BluetoothSocket to connect with the given BluetoothDevice.
            // MY_UUID is the app's UUID string, also used in the server code.
            UUID uuid = UUID.fromString("F814E012-48FE-44F4-AF94-9D9C4CF7495A");
            tmp = device.createRfcommSocketToServiceRecord(uuid);
        } catch (IOException e) {
            Log.e(TAG, "Socket's create() method failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it otherwise slows down the connection.
        MainActivity.mBluetoothAdapter.cancelDiscovery();

        try {
            // Connect to the remote device through the socket. This call blocks
            // until it succeeds or throws an exception.
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and return.
            try {
                mmSocket.close();
            } catch (IOException closeException) {
                Log.e(TAG, "Could not close the client socket", closeException);
            }
            return;
        }

        // The connection attempt succeeded. Perform work associated with
        // the connection in a separate thread.

        MainActivity.mState = 1;
    }

    public void write(byte[] bytes) {
        try {
            OutputStream outputStream = mmSocket.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Closes the client socket and causes the thread to finish.
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "Could not close the client socket", e);
        }
    }



}

1 个答案:

答案 0 :(得分:0)

确定。这是我不理解线程。问题是我使用的是thread.run()而不是thread.start()。