시리얼 데이터를 전송하는 블루투스 송수신기에 연결하는 블루투스 앱을 만들고 있습니다. 블루투스 장치는 결국 센서에 연결되며이 센서는 내 휴대 전화에 표시해야하는 데이터를 제공합니다. 현재 시뮬레이션 소프트웨어 인 CoolTerm을 사용하여 내 앱과 외부 블루투스 기기간에 데이터를주고 받고 있습니다. 현재 앱에서 기기를 감지하고 연결하도록 만들었습니다.Android 애플리케이션 통신 시리얼 데이터
는 첫째 하나가 (Mac에서 사용 가능한을 창문 기술적으로 말하기) CoolTerm를 설치하는 방법을 알고 않습니다,하지만 난 우분투를 설치하려고 할 때 같은 실행 가능 파일을 제공하지 :하지만 몇 가지 문제로 실행하고 있습니다 그것은 창문에했다. 우분투에서 이것을 설치하는 방법을 알고있는 사람이라면 이미 웹 사이트에서 리눅스 버전 타르볼을 다운로드하고 압축을 푼 단계를 알려주십시오.
성공적으로 연결되면 내 앱에서 Bluetooth 장치가 수신 한 문자열을 전송하지만 데이터를 다시받을 수는 없습니다. 내가 현재 설정 한 방식으로 외부 Bluetooth 장치가 나에게 전송할 때 데이터를 수신했다는 팝업 메시지가 나타납니다. CoolTerm 소프트웨어는 데이터를 보낼 수 있지만 이것은 내 애플 리케이션에 표시되지 않는 이유입니다. 어떤 아이디어?
마지막으로 누구나 내 응용 프로그램에서 외부 블루투스 장치로 데이터를 보낼 수있는 좋은 텍스트 상자 위젯이나 기타 기능을 알고 있습니다. 지금 당장은 앱이 연결되는 즉시 문자열을 보냅니다.
다음은 YouTube 링크입니다. 코드가 제안하는대로 약간 변경했습니다.
[여기] (http://www.youtube.com/watch?v=r55C77_ohi8 "youtube video of app")를 클릭하십시오! [여기]를 클릭하십시오 (https://drive.google.com/?tab=mo&authuser=0#folders/0BwRY4KO_k7sUSGpLX0o4TDFCOFk "클리너 코드 formmatt")! 기기 모듈에서 루프 백 연결 (RXD으로, 즉 짧은 TXD)를 확인한 후, "UART 변환기 블루투스 '모듈 경우
여기서 코드
package com.example.intellicyclemobileside;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton toggle_discovery;
Button button;
ListView listView;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mArrayAdapter;
ArrayAdapter<String> adapter;
ArrayList<String> pairedDevicesList;
ArrayList<String> unpairedDevicesList;
ArrayList<String> combinedDevicesList;
Set<BluetoothDevice> pairedDevices;
Set<String> unpairedDevices;
BroadcastReceiver mReceiver;
String selectedFromList;
String selectedFromListName;
String selectedFromListAddress;
BluetoothDevice selectedDevice;
/*
public BluetoothSocket mmSocket;
public BluetoothDevice mmDevice;*/
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
final int STATE_CONNECTED = 2;
final int STATE_CONNECTING = 1;
final int STATE_DISCONNECTED = 0;
private final UUID MY_UUID = UUID.fromString("0001101-0000-1000-8000-00805F9B34FB");
private static final int REQUEST_ENABLE_BT = 1;
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// Do Something;
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(),"CONNECTED",0).show();
String s = "This string proves a socket connection has been established!!";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(),string,0).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.findDevices);
toggle_discovery = (ToggleButton) findViewById(R.id.deviceDiscoverable);
pairedDevicesList = new ArrayList<String>();
unpairedDevicesList = new ArrayList<String>();
unpairedDevices = new HashSet<String>();
listView = (ListView)findViewById(R.id.listView);
// Sets up Bluetooth
enableBT();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "Searching for devices, please wait... ",Toast.LENGTH_SHORT).show();
// Checks for known paired devices
pairedDevices = mBluetoothAdapter.getBondedDevices();
displayCominedDevices();
//mBluetoothAdapter.cancelDiscovery();
}
});
toggle_discovery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
makeDicoverable(1);
} else {
// The toggle is disabled
makeDicoverable(0);
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// When clicked, show a toast with the TextView text
selectedFromList = (String) (listView.getItemAtPosition(position));
/*Debugging
Toast.makeText(getApplicationContext(), selectedFromList,Toast.LENGTH_SHORT).show();*/
String[] parts = selectedFromList.split(" ");
selectedFromListName = parts[0];
selectedFromListAddress = parts[1];
BluetoothDevice selectedDevice = selectedDevice(selectedFromListAddress);
mBluetoothAdapter.cancelDiscovery();
ConnectThread ct = new ConnectThread(selectedDevice);
ct.start();
//ConnectThread ConnectThread = new ConnectThread(selectedDevice);
//connectDevice();
/* Debug Help
Toast.makeText(getApplicationContext(), selectedFromListName,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), selectedFromListAddress,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),selectedDevice.getAddress(), Toast.LENGTH_SHORT).show();*/
}
});
}
public void displayCominedDevices(){
displayPairedDevices();
displayDetectedDevices();
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,removeDuplicates(unpairedDevicesList,pairedDevicesList));
listView.setAdapter(mArrayAdapter);
}
public BluetoothDevice selectedDevice(String deviceAddress){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
return device;
}
@SuppressLint("NewApi")
public String checkState(BluetoothSocket mmSocket2){
String state = "NOT_KNOWN";
if (mmSocket2.isConnected() == true){
state = "STATE_CONNECTED";
}
state = "STATE_DISCONNECTED";
Toast.makeText(getApplicationContext(), state, Toast.LENGTH_SHORT).show();
return state;
}
@SuppressWarnings("unchecked")
public ArrayList<String> removeDuplicates(ArrayList<String> s1, ArrayList<String> s2){
/*Debugging
Toast.makeText(getApplication(), "unpairedList " + s1.toString(),Toast.LENGTH_LONG).show();
Toast.makeText(getApplication(), "pairedList " + s2.toString(),Toast.LENGTH_LONG).show(); */
combinedDevicesList = new ArrayList<String>();
combinedDevicesList.addAll(s1);
combinedDevicesList.addAll(s2);
@SuppressWarnings("unchecked")
Set Unique_set = new HashSet(combinedDevicesList);
combinedDevicesList = new ArrayList<String>(Unique_set);
/*Debugging
Toast.makeText(getApplication(),"Combined List" + combinedDevicesList.toString(),Toast.LENGTH_LONG).show(); */
return combinedDevicesList;
}
public void enableBT(){
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "Bluetooth is not suppourted on Device",Toast.LENGTH_SHORT).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
int resultCode = Activity.RESULT_OK;
if(resultCode < 1){
Toast.makeText(getApplicationContext(), "Please Accept Enabling Bluetooth Request!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Enabling Bluetooth FAILED!", Toast.LENGTH_SHORT).show();
}
}
}
public void displayPairedDevices(){
// If there are paired devices
enableBT();
if (pairedDevices.size() > 0) {
//Toast.makeText(getApplicationContext(),"in loop",Toast.LENGTH_SHORT).show();
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
String s = " ";
String deviceName = device.getName();
String deviceAddress = device.getAddress();
pairedDevicesList.add(deviceName + s + deviceAddress +" \n");
//listView.setAdapter(mArrayAdapter);
//Toast.makeText(getApplicationContext(), device.getName(),Toast.LENGTH_SHORT).show();
}
/*
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,pairedDevicesList);
listView.setAdapter(mArrayAdapter);*/
}
}
public void displayDetectedDevices(){
mBluetoothAdapter.startDiscovery();
// Create a BroadcastReceiver for ACTION_FOUND
mReceiver = new BroadcastReceiver() {
@SuppressWarnings("static-access")
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/* Debugging help
Toast.makeText(getApplicationContext(),action,Toast.LENGTH_SHORT).show();*/
// When discovery finds a device
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
/* Debugging help
Toast.makeText(getApplicationContext(),device.getName(),Toast.LENGTH_SHORT).show();*/
String deviceName = device.getName();
String deviceAddress = device.getAddress();
String s = " ";
unpairedDevices.add(deviceName + s + deviceAddress +" \n");
//unpairedDevicesList.add(deviceName + s + deviceAddress +" (un-paired)\n");
unpairedDevicesList = new ArrayList<String>(unpairedDevices);
}
}
};
/*adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,unpairedDevicesList);
listView.setAdapter(adapter);*/
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
//Toast.makeText(getApplicationContext(), unpairedDevicesList.toString(), Toast.LENGTH_LONG).show();
}
public void makeDicoverable(int option){
Intent discoverableIntent;
if (option == 1){
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery for 2mins", Toast.LENGTH_SHORT).show();
} else {
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery is OFF!", Toast.LENGTH_SHORT).show();
}
}
/*Un-used Method
public void compareAddress(BluetoothDevice checkDevice,String address){
if((checkDevice.getAddress().equals(address))){
selectedDevice = checkDevice;
}
}*/
@SuppressLint("NewApi")
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
Toast.makeText(getApplicationContext(), "Connecting to device failed!", Toast.LENGTH_LONG).show();
}
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = 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; // 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
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
}
}