【问题标题】:Thread already started- trans data via bluetooth线程已经开始-通过蓝牙传输数据
【发布时间】:2016-08-24 20:48:29
【问题描述】:

这是我的:bluetooth.java。当我测试我的应用程序时,它会跳出这个错误“线程已经启动。然后我不能再发送我的数据,然后我退出我的应用程序,然后我再次启动我的应用程序,然后它允许我使用应用程序。 如此混乱。 我希望你能帮助我。 感谢您的帮助。

public class bluetooth extends AppCompatActivity {

// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth);
    on = (ImageView) findViewById(R.id.btn_enable);
    find = (ImageView) findViewById(R.id.btn_scan);
    mPairedBtn = (ImageView) findViewById(R.id.btn_view_paired);
    BA = BluetoothAdapter.getDefaultAdapter();
    mProgressDlg = new ProgressDialog(this);
    back =(ImageView) findViewById(R.id.backblue);
    ontext = (TextView) findViewById(R.id.connecttext);

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(bluetooth.this,MainActivity.class);
            startActivity(intent);
        }
    });



    //xử lí các nút
    if (BA == null) {
        showUnsupported();
    } else {
        mPairedBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Set<BluetoothDevice> pairedDevices = BA.getBondedDevices();

                if (pairedDevices == null || pairedDevices.size() == 0) {
                    showToast("No Paired Devices Found");
                } else {
                    ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();

                    list.addAll(pairedDevices);

                    Intent intent = new Intent(bluetooth.this, DeviceListActivity.class);

                    intent.putParcelableArrayListExtra("device.list", list);

                    startActivity(intent);
                }
            }
        });

        find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                BA.startDiscovery();
            }
        });

        on.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (BA.isEnabled()) {
                    BA.disable();
                    showDisabled();
                   /* try
                    {
                        btSocket.close();
                    } catch (IOException e2)
                    {

                    }*/
                    on.setImageResource(R.drawable.offlight);

                } else {
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

                    startActivityForResult(intent, 1000);

                    on.setImageResource(R.drawable.onlight);

                }
            }
        });

        if (BA.isEnabled()) {
            showEnabled();

        } else {
            showDisabled();
        }
    }

    //thong bao cho may la chuong trinh nay co he su dung dc gi bluetooth
    IntentFilter filter = new IntentFilter();

    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    /* BroadcastReceiver dùng để nhận các intent từ hệ thống hoặc trao đổi dữ liệu giữa hai hay nhiều ứng dụng.*/
    registerReceiver(mReceiver, filter);


    // MAC-address of Bluetooth module (you must edit this line)
    address = "30:14:10:09:07:86";

    //create device and set the MAC address
    BluetoothDevice device = BA.getRemoteDevice(address);

    try {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
    }
    // Establish the Bluetooth socket connection.
    //btSocket.connect();
    try
    {
        btSocket.connect();
    } catch (IOException e) {
        try
        {
            btSocket.close();
        } catch (IOException e2)
        {
            //insert code to deal with this
            Toast.makeText(getApplicationContext(),"cant do this",Toast.LENGTH_LONG).show();
        }
    }

    ConnectedThread.createInstance(btSocket);


    //I send a character when resuming.beginning transmission to check device is connected
    //If it is not an exception will be thrown in the write method and finish() will be called
    if(ConnectedThread.getInstance()!= null){
        ConnectedThread.getInstance().start();
    }else {
        ConnectedThread.getInstance().cancel();
    }


}

@Override
public void onResume() {
    super.onResume();



}

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

    return  device.createRfcommSocketToServiceRecord(MY_UUID);
    //creates secure outgoing connecetion with BT device using UUID
}

@Override
public void onPause() {
    super.onPause();

}

@Override
public void onDestroy() {
    unregisterReceiver(mReceiver);
    super.onDestroy();
}




private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

            if (state == BluetoothAdapter.STATE_ON) {
                showToast("Enabled");

                showEnabled();
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
            mDeviceList = new ArrayList<BluetoothDevice>();

            mProgressDlg.show();
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            mProgressDlg.dismiss();

            Intent newIntent = new Intent(bluetooth.this, DeviceListActivity.class);

            newIntent.putParcelableArrayListExtra("device.list", mDeviceList);

            startActivity(newIntent);
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            mDeviceList.add(device);

            showToast("Found device " + device.getName());
        }
    }
};

}

【问题讨论】:

  • 您要连接哪种蓝牙模块?
  • @A.Omar : hc 05 (with aduino)

标签: android multithreading android-activity bluetooth onresume


【解决方案1】:

这是我做的一个库,你可以试试看:

https://github.com/omaflak/Bluetooth-Android

它与 HC-06 完美配合,对你来说应该是一样的。这就是我使用课程的方式:

Bluetooth bt = new Bluetooth();
bt.enableBluetooth();

bt.setBluetoothCallback(new Bluetooth.BluetoothCallback() {
    @Override
    public void onConnect(BluetoothDevice device) {
        bt.send("hello world!");
    }

    @Override
    public void onDisconnect(BluetoothDevice device, String message) {
        Log.e(TAG, "Disconnected!");
    }

    @Override
    public void onMessage(String message) {
        Log.e(TAG, "Received: "+message);
    }

    @Override
    public void onError(String message) {
        Log.e(TAG, "Error: "+message);
    }

    @Override
    public void onConnectError(BluetoothDevice device, String message) {
        Log.e(TAG, message);
        bt.connectToDevice(device); // try to connect again
    }
});

/*
    Connection...
    /!\ you must be paired with the device via the settings app /!\
*/
bt.connectToName("HC-06");   
//you can also connect with:   bt.connectToAddress(address) and bt.connectToDevice(device)

编辑: 在 Arduino 方面,您必须在每条消息的末尾添加 \n。您可以简单地使用 yourSerial.println("message")。

EDIT2:您可以在这里找到我的 Arduino 代码:https://causeyourestuck.io/2015/12/14/communication-between-android-and-hc-06-module/

【讨论】:

    【解决方案2】:

    我知道我的回答来晚了,但我想提一下(并链接)一个非常简单易用的基于消息的 Android 蓝牙库,希望它对某人有用:

    https://github.com/BasicAirData/BluetoothHelper

    它是 Android 设备(客户端)和微控制器(服务器)之间基于消息的简单蓝牙无线通信层,可与任何基于 Arduino 的微控制器和蓝牙接口(如便宜的 HC-05)一起使用。
    它是根据 GPL-3 条款获得许可的。

    设置非常简单:

    1. 向您的 AndroidManifest.xml 添加蓝牙权限:
        <uses-permission android:name = "android.permission.BLUETOOTH_ADMIN"/>
        <uses-permission android:name = "android.permission.BLUETOOTH"/>
    
    1. 在 Activity 中声明一个新的 BluetoothHelper 实例:
        BluetoothHelper mBluetoothHelper = new BluetoothHelper();
    
    1. 设置 BluetoothHelperListener 以接收消息和连接状态的变化:
        mBluetoothHelper.setBluetoothHelperListener(new BluetoothHelper.BluetoothHelperListener() {
            @Override
            public void onBluetoothHelperMessageReceived(BluetoothHelper bluetoothhelper, final String message) {
                // Do something with the message received
                // runOnUiThread(new Runnable() {
                //     @Override
                //     public void run() {
                //         // Update your UI
                //     }
                // });
            }
        
            @Override
            public void onBluetoothHelperConnectionStateChanged(BluetoothHelper bluetoothhelper, boolean isConnected) {
                // Do something, depending on the new connection status
            }
        });
    

    用法更简单:

    • 与配对设备连接:
    mBluetoothHelper.Connect(mBluetoothDevice);
    // mBluetoothHelper.Connect("HC-05");    <-- use it as alternative
    
    • 发送消息:
    mBluetoothHelper.SendMessage("Hello World");
    
    • 检查连接状态:
    mBluetoothHelper.isConnected();
    
    • 断开连接
    mBluetoothHelper.Disconnect();
    

    GitHub 页面上有大量文档、一个包含 Android 和 Arduino 代码的基本示例,以及一个简单但功能齐全的开源应用程序的链接,该应用程序使用 HC-05 与 Arduino 连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多