我在尝试发送存储在textAdim
变量中的数据时遇到问题。我期望变量是0到10之间的int,但是我接收255或254作为值。请帮帮我
这是我的代码:
package com.led_on_off.led;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.util.Random;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import java.io.IOException;
import java.util.UUID;
public class ledControl extends ActionBarActivity implements SensorEventListener {
SensorManager sm;
TextView tv;
int stepsCount = 0;
private boolean mInitialized;
double mLastX;
double mLastY;
double mLastZ;
int textAdim = 0;
private final float NOISE = (float) 2.0;
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
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);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
tv=(TextView)findViewById(R.id.text1);
mInitialized = false;
//get sensor service
sm=(SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
//Tell which sensor you are going to use
//And declare delay of sensor
//Register all to your sensor object to use
sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
//call the widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
new ConnectBT().execute(); //Call the class to connect
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(String.valueOf(textAdim).getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_led_control, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
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(ledControl.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
}
}
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)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
// TODO Auto-generated method stub
}
//This method is called when your mobile moves any direction
@Override
public void onSensorChanged(SensorEvent event) {
// event object contains values of acceleration, read those
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
final double alpha = 0.8; // constant for our filter below
double[] gravity = {0,0,0};
// Isolate the force of gravity with the low-pass filter.
gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
// Remove the gravity contribution with the high-pass filter.
x = event.values[0] - gravity[0];
y = event.values[1] - gravity[1];
z = event.values[2] - gravity[2];
if (!mInitialized) {
// sensor is used for the first time, initialize the last read values
double mLastX = x;
double mLastY = y;
double mLastZ = z;
mInitialized = true;
} else {
// sensor is already initialized, and we have previously read values.
// take difference of past and current values and decide which
// axis acceleration was detected by comparing values
double deltaX = Math.abs(mLastX - x);
double deltaY = Math.abs(mLastY - y);
double deltaZ = Math.abs(mLastZ - z);
if (deltaX < NOISE)
deltaX = (float) 0.0;
if (deltaY < NOISE)
deltaY = (float) 0.0;
if (deltaZ < NOISE)
deltaZ = (float) 0.0;
mLastX = x;
mLastY = y;
mLastZ = z;
if (deltaX > deltaY) {
// Horizontal shake
// do something here if you like
} else if (deltaY > deltaX) {
// Vertical shake
// do something here if you like
} else if ((deltaZ > deltaX) && (deltaZ > deltaY)) {
// Z shake
stepsCount = stepsCount + 1;
if (stepsCount > 0) {
tv.setText(String.valueOf(stepsCount));
textAdim = stepsCount;
}
// Just for indication purpose, I have added vibrate function
// whenever our count moves past multiple of 10
}
}
}
}
答案 0 :(得分:0)
您正在写入传递二进制数据的流。使用String.valueOf(textAdim).getBytes()
时,您首先将int
转换为String
,然后将其转换为String
的二进制表示形式。为了读取流的另一侧的值,您需要首先解码数据。
我认为这个answer可以很好地解释发生了什么。