我正在尝试从Android / Java程序向Arduino发送和读取数据。已成功发送https://www.instructables.com/id/Android-Arduino-Bluetooth-PC-Game-Controller/的此代码示例,但无法使我的代码读取传感器数据。因此,我尝试编写自己的读取数据处理程序beginListenForData()
我尝试过https://github.com/googlesamples/android-BluetoothChat,但是我的Java技能不足以满足我的需求。
package com.example.arm_avi.androidarduinogamepad;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.zip.DeflaterInputStream;
public class GameControllerActivity extends AppCompatActivity {
Button upBtn, downBtn, leftBtn, rightBtn, assignOneBtn, assignTwoBtn, backbtn, enterBtn, disconnBtn;
public Handler bluetoothIn;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_controller);
getSupportActionBar().hide();
Intent newint = getIntent();
address = newint.getStringExtra(BluetoothListActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
//call the widgtes
/* btnOn = (Button)findViewById(R.id.upBtn);
btnOff = (Button)findViewById(R.id.leftBtn);
disconnBtn = (Button)findViewById(R.id.disconnBtn);*/
upBtn = (Button) findViewById(R.id.upBtn);
downBtn = (Button) findViewById(R.id.downBtn);
leftBtn = (Button) findViewById(R.id.leftBtn);
rightBtn = (Button) findViewById(R.id.rightBtn);
backbtn = (Button) findViewById(R.id.backBtn);
enterBtn = (Button) findViewById(R.id.enterBtn);
assignOneBtn = (Button) findViewById(R.id.assignOne);
assignTwoBtn = (Button) findViewById(R.id.assignTwo);
disconnBtn = (Button)findViewById(R.id.disconnBtn);
new ConnectBT().execute();
upBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
upDirection();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
downBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
downDirection();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
leftBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
leftDirection();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
rightBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
rightDirection();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
enterBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
enter();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
backbtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
back();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
assignOneBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
assignKeyOneFunc();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
assignTwoBtn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case (MotionEvent.ACTION_DOWN):
assignKeyTwoFunc();
return true;
case (MotionEvent.ACTION_UP):
keyBoardRelease();
return true;
}
return false;
}
});
disconnBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
void beginListenForData()
{
final Handler handler = new Handler();
byte[] buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted())
{
if (btSocket!=null)
{
handler.post(new Runnable() {
public void run()
{
Toast.makeText(getApplicationContext(), btSocket.getInputStream().read(),Toast.LENGTH_LONG).show();
}
});
}
}
}
});
thread.start();
}
/* Handler thread */
// Up Navigation Function which send 1 to instructs Keyboard Up Direction
private void upDirection()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("11".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// Down Navigation Function which send 2 to instructs Keyboard Down Direction
private void downDirection()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("2".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// Left Navigation Function which send 3 to instructs Keyboard Left Direction
private void leftDirection()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("3".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// Right Navigation Function which send 4 to instructs Keyboard Right Direction
private void rightDirection()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("4".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// Enter Function which send 5 to Press Enter
private void enter()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("5".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// Back Function which send 6 to Press BackSpace
private void back()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("6".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// MouseClick Function which send 6 to Press Mouse Left Button
private void assignKeyOneFunc()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("7".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
private void assignKeyTwoFunc()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("8".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// KeyRelease Function which send 0 to instructs Keyboard for release kryBoard Key
private void keyBoardRelease()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
}
// Disconnect the HC-05 Bluetooth Module
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
}
finish(); //return to the first layout
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(GameControllerActivity.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
beginListenForData();
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
@Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
Toast.makeText(getApplicationContext(),"Not Connected!",Toast.LENGTH_SHORT).show();
finish();
}
else
{
Toast.makeText(getApplicationContext(),"Successfully Connected",Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
progress.dismiss();
}
}
}
我希望读取将由函数beginListenForData()读取的Arduino传感器数据;但它可以使程序崩溃而不会出现任何错误。