Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android Bluetooth在添加断点时发送消息,但如果程序不';不要停顿_Java_Android_Bluetooth - Fatal编程技术网

Java Android Bluetooth在添加断点时发送消息,但如果程序不';不要停顿

Java Android Bluetooth在添加断点时发送消息,但如果程序不';不要停顿,java,android,bluetooth,Java,Android,Bluetooth,我有以下与计算机上的C#程序对话的代码。当我在outputStream.write(字节)代码之前添加断点时,当我重新启动程序时,它可以正常工作。如果我让程序运行,它不会发送消息。我认为这与时间有关,但我已经尽了我所能确保英国电信在发送信息之前已连接 单击按钮即可发送消息 以下是两个类: MainActivity.java public class MainActivity extends AppCompatActivity implements View.OnClickListener {

我有以下与计算机上的C#程序对话的代码。当我在outputStream.write(字节)代码之前添加断点时,当我重新启动程序时,它可以正常工作。如果我让程序运行,它不会发送消息。我认为这与时间有关,但我已经尽了我所能确保英国电信在发送信息之前已连接

单击按钮即可发送消息

以下是两个类:

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

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

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



}