我正在努力解决蓝牙应用程序的一些问题。该应用程序通过蓝牙连接到OBD2接口,我的目标是从我的汽车接收一些数据,如速度,RPM等。
我制作了一个带有按钮的应用程序当我点击它时,我向OBD2界面发送一条消息,我得到了回复。但我的目标是不断收到这些数据。所以我发现我可以在里面做到这一点
onResume()
方法。下面是发送消息的简单代码。
@Override
protected void onResume() {
super.onResume();
HandlerDelay.postDelayed(new Runnable() {
@Override
public void run() {
checkSPDstatus();
}
},500);
}
private void checkSPDstatus(){
if (mmSocket != null){
try {
mmSocket.getOutputStream().write("010C\r".getBytes());
} catch (IOException e) {
Log.e("Status", String.valueOf(e));
}
}
}
但使用我的应用程序崩溃,甚至无法连接BT设备.. 使用AsyncTask通过BT Im连接我的应用程序。我将不胜感激任何帮助。
关心马特。
答案 0 :(得分:0)
好的,我想出了如何做到这一点。我使用Service来连接蓝牙设备而不是AsyncTask。我使用了两个处理程序。现在一切正常。我可以每500ms发送一次String消息,也可以从OBD2接口获得响应。以下是服务类的代码。 我使用BroadcastReceiver从Service接收数据到我的UI。
public class BTConnect extends Service {
private BluetoothAdapter btAdapter;
private String adress;
private static UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothSocket mmSocket;
private boolean isBTConnected = false;
private ConnectedThread mConncetedThread;
Handler h;
Handler HandlerDelay = new Handler();
final int handlerState = 0;
public StringBuilder recDataString = new StringBuilder();
private Timer mTimer;
final static String MY_ACTION = "MY_ACTION";
public BTConnect() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
if(mTimer != null) {
mTimer.cancel();
} else {
mTimer = new Timer();
}
mTimer.scheduleAtFixedRate(new TimerDisplay(), 0, 500);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String adressMac = intent.getStringExtra("MAC_ADRESS");
// Trzeba sie połączyć
h = new MyHandler();
tryToConnect(adressMac);
return START_NOT_STICKY;
}
private void tryToConnect(String address) {
try {
if (mmSocket == null || !isBTConnected) {
btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = btAdapter.getRemoteDevice(address);
mmSocket = device.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mmSocket.connect();
isBTConnected = true;
mConncetedThread = new ConnectedThread(mmSocket);
mConncetedThread.start();
}
} catch (IOException e) {
Log.e("Error", String.valueOf(e));
}
if (isBTConnected) {
Log.d("Status", "Connected");
Toast.makeText(getBaseContext(), "Connected", Toast.LENGTH_LONG);
}
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
@Override
public void run() {
super.run();
byte[] mmBuffer = new byte[1024];
int mmBytes;
//Start Listening
while(true) {
try {
mmBytes = mmInStream.read(mmBuffer);
Message readMsg = h.obtainMessage(handlerState, mmBytes, -1, mmBuffer);
readMsg.sendToTarget();
} catch (IOException e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "Input stream was disconnected", Toast.LENGTH_LONG).show();
break;
}
}
}
public void write(){
try {
mmSocket.getOutputStream().write("010C\r".getBytes());
} catch (IOException e) {
Log.e("Error", String.valueOf(e));
}
}
}
private class MyHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == handlerState) {
Intent sendIntent = new Intent();
byte[] rBuff = (byte[]) msg.obj; // recived message (bytes)
String readMessage = new String(rBuff, 0, msg.arg1); // convert that message to string
recDataString.append(readMessage);
Log.d("Tab", String.valueOf(recDataString));
int startOfIndex = recDataString.indexOf("41 0C");
int stopIndex = recDataString.indexOf(">");
if (stopIndex > 0) {
Log.d("RedVal", String.valueOf(recDataString));
String msg1 = String.valueOf(recDataString);
sendIntent.putExtra("SEND_MESSAGE", msg1);
sendIntent.setAction(MY_ACTION);
sendBroadcast(sendIntent);
recDataString.delete(0, recDataString.length());
} else if(recDataString.length() > 33) {
String msg1 = String.valueOf(recDataString.substring(recDataString.length()-26, recDataString.length()));
sendIntent.putExtra("SEND_MESSAGE", msg1);
sendIntent.setAction(MY_ACTION);
sendBroadcast(sendIntent);
recDataString.delete(0, recDataString.length());
}
}
}
}
class TimerDisplay extends TimerTask {
@Override
public void run() {
HandlerDelay.postDelayed(new Runnable() {
@Override
public void run() {
mConncetedThread.write();
}
},500);
}
}
}