어디서나 내 특정 문제에 대한 답변을 찾을 수 없습니다.여러 활동에 걸쳐 Bluetooth 연결을 유지하는 방법은 무엇입니까?
내 응용 프로그램 활동이 모두 Bluetooth 연결로 데이터를 개별적으로 교환 할 수있는 방법이 필요합니다. 여기에 내가하고자하는 일이있다 :
나는 각각 새로운 활동을 시작하는 많은 버튼이있는 주요 활동이있다. 단추 중 하나가 Bluetooth 연결을 설정해야합니다. 생성 된 후에는 주 활동으로 돌아가서 다른 단추를 눌러 이전에 만든 Bluetooth 연결에서 데이터를 보내고받을 수있는 새로운 활동을 열 수 있기를 원합니다.
나는 java/android에서 새로운 편이지만 도움이 절실히 필요하다. 팀 프로젝트를 위해이 앱을 설정해야하기 때문에 도움이 필요하다. 현재 저는 인터넷을 통해 시작될 때 특정 BT 모듈에 간단하게 연결되는 앱을 만들기 위해 약간의 코드를 모으고 있습니다. 그러나 새로운 페이지 (활동)를 열 수없는 경우이 앱은 쓸모가 없습니다.
connectBluetooth 및 sendReceiveBytes의 클래스는 모두 스레드로 시작됩니다. 그러나 나는 그 실이 그들이 시작된 활동이 죽을 때 죽는다고 믿습니다 (주요 활동). 그래서 어쨌든이 일을 할 수 있다면 제게 계몽 해주십시오. 또는 더 많은 정보가 필요하면 알려 주시기 바랍니다. 모두에게 감사드립니다!
내 코드는 다음과 같습니다. 이것은 단순히 "RNBT-504D"라는 bt 장치에 즉시 연결되는 단일 시작 작업입니다. 그리고 응용 프로그램을 종료하고 활동이 종료되면 onDestroy 메서드로 인해 연결이 닫힙니다.
연결 스레드를 시작하고 성공하면 관리 연결 스레드 (sendReceiveBytes)를 시작하는 브로드 캐스트 수신기를 보여 줬습니다. 세 가지 클래스가 아래에 나와 있습니다.
/* This BroadcastReceiver will display discovered Bluetooth devices */
public class myOwnBroadcastReceiver extends BroadcastReceiver {
ConnectToBluetooth connectBT;
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
//Notification that BluetoothDevice is FOUND
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//Gather information about discovered bluetooth device
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Display more information about the discovered device
if(discoveredDevice.getName().equals("RNBT-504D")){
ToastMaster("Device: " + discoveredDevice.getName() +"\n"+ discoveredDevice.getAddress());
}
//Connect to the discovered Bluetooth device (SeeedBTSlave)
if (discoveredDevice.getName().equals("RNBT-504D")) {
ToastMaster("Connecting you Now !!");
unregisterReceiver(myDiscoverer);
connectBT = new ConnectToBluetooth(discoveredDevice);
//Connect to the the device in a new thread
new Thread(connectBT).start();
}
}
//Notification if bluetooth device is connected
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
ToastMaster("CONNECTED _ YAY");
while (scSocket==null) {
//do nothing
}
if (scSocket!=null) {
sendReceiveBT = new SendReceiveBytes(scSocket);
new Thread(sendReceiveBT).start();
//String red = "r";
//byte[] myByte = stringToBytesUTFCustom(red);
byte[] pronto = new byte[]{0x00, 0x00, 0x00, 0x6E, 0x00, 0x22, 0x00, 0x02, 0x01, 0x56, 0x00, (byte) 0xAC, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x05, (byte) 0x8C, 0x01, 0x56, 0x00, 0x56, 0x00, 0x15, 0x0E, 0x44};
sendReceiveBT.write(pronto);
}
}
if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
ToastMaster("Disconnected from "+discoveredDevice.getName());
}
}
}
public static byte[] stringToBytesUTFCustom(String str) {
char[] buffer = str.toCharArray();
byte[] b = new byte[buffer.length << 1];
for (int i = 0; i < buffer.length; i++) {
int bpos = i << 1;
b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
b[bpos + 1] = (byte) (buffer[i]&0x00FF);
}
return b;
}
public class ConnectToBluetooth implements Runnable {
private BluetoothDevice btShield;
private BluetoothSocket mySocket = null;
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
btShield = bluetoothShield;
try {
mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
}
catch(IOException createSocketException) {
//Problem with creating a socket
Log.e("ConnectToBluetooth", "Error with Socket");
}
}
@Override
public void run() {
/* Cancel discovery on Bluetooth Adapter to prevent slow connection */
bluetooth.cancelDiscovery();
try {
/*Connect to the bluetoothShield through the Socket. This will block
until it succeeds or throws an IOException */
mySocket.connect();
scSocket=mySocket;
}
catch (IOException connectException) {
Log.e("ConnectToBluetooth", "Error with Socket Connection");
try {
mySocket.close(); //try to close the socket
}
catch(IOException closeException) {
}
return;
}
}
/* Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mySocket.close();
}
catch (IOException e) {
}
}
}
private class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private InputStream btInputStream = null;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try {
btInputStream = btSocket.getInputStream();
btOutputStream = btSocket.getOutputStream();
}
catch (IOException streamError) {
Log.e(TAG, "Error when getting input or output Stream");
}
}
public void run() {
byte[] buffer = new byte[1024]; // 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 = btInputStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
catch (IOException e) {
Log.e(TAG, "Error reading from btInputStream");
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes);
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
btSocket.close();
}
catch (IOException e) {
Log.e(TAG, "Error when closing the btSocket");
}
}
}