我試圖用MainActivity和SensorEventListener製作應用程序。來自加速計的數據將保存在結構(類,兩個int變量)中。 我創建了應用程序啓動後運行的UDP客戶端線程。 UDP客戶端將這兩個變量發送到遠程服務器。Android:通過UDP從線程發送加速度計數據
問題是我需要知道什麼時候傳感器刷新數據,然後通過UDP客戶端(另一個線程)發送數據。 Im新的Android應用程序和Java。 如果你能給我一些代碼示例如何做,這將是非常有幫助的。
代碼:
public class MainActivity extends Activity implements SensorEventListener {
Button button;
String theLine = null;
public static final String SERVERIP = "192.168.2.101"; // 'Within' the emulator!
public static final int SERVERPORT = 12345;
private static final int RESULT_SETTINGS = 1;
public boolean bKeepRunning;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
Client client = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
public class Client extends Thread
{
bKeepRunning = true;
@Override
public void run()
{
byte[] sendData = new byte[512];
sendData =intToByteArray(angles.rolling, angles.pitching);
sendData= reverseArray(sendData);
InetAddress serverAddr = null;
try{
serverAddr = InetAddress.getByName(SERVERIP);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
DatagramPacket packet = new DatagramPacket(sendData, sendData.length, serverAddr, SERVERPORT);
try {
DatagramSocket socket = new DatagramSocket();
while(bKeepRunning)
{
socket.send(packet);
}
}catch (Exception e) {
}
}
public void kill()
{
bKeepRunning = false;
}
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, SecondActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
break;
case R.id.about_us:
Intent j = new Intent(this, UserSettings.class);
startActivityForResult(j, RESULT_SETTINGS);
break;
}
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
showUserSettings();
break;
}
}
public void showUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n IP Address: " + sharedPrefs.getString("prefipaddress", "NULL"));
builder.append("\n Port: " + sharedPrefs.getString("prefport", "NULL"));
TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);
settingsTextView.setText(builder.toString());
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
client = new Client();
client.start();
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
client.kill();
}
public static class angles
{
static int rolling;
static int pitching;
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
final float alpha = (float) 0.9;
float[] gravity = new float[3];
float[] linear_acceleration = new float[3];
TextView tvX= (TextView)findViewById(R.id.roll);
TextView tvY= (TextView)findViewById(R.id.pitch);
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];
linear_acceleration[0] = event.values[0] - gravity[0];
linear_acceleration[1] = event.values[1] - gravity[1];
linear_acceleration[2] = event.values[2] - gravity[2];
String linear_acceleration0 = String.format("%.2f", linear_acceleration[0]).replace(",",".");
String linear_acceleration1 = String.format("%.2f", linear_acceleration[1]).replace(",",".");
String linear_acceleration2 = String.format("%.2f", linear_acceleration[2]).replace(",",".");
linear_acceleration[0] = Float.parseFloat(linear_acceleration0);
linear_acceleration[1] = Float.parseFloat(linear_acceleration1);
linear_acceleration[2] = Float.parseFloat(linear_acceleration2);
//float rotation = (float) (Math.atan2(linear_acceleration[0], linear_acceleration[1])/(Math.PI/180));
float roll = (float) Math.toDegrees(Math.atan(linear_acceleration[0]/Math.sqrt(Math.pow(linear_acceleration[1], 2) + Math.pow(linear_acceleration[2], 2))));
float pitch = (float) Math.toDegrees(Math.atan(linear_acceleration[1]/Math.sqrt(Math.pow(linear_acceleration[0], 2) + Math.pow(linear_acceleration[2], 2))));
float yaw = (float) Math.toDegrees(Math.atan(Math.sqrt(Math.pow(linear_acceleration[0], 2) + Math.pow(linear_acceleration[1], 2))/linear_acceleration[2]));
String roll_print = String.format("%.2f", roll);
String pitch_print = String.format("%.2f", pitch);
roll_print = roll_print.replace(",",".");
pitch_print = pitch_print.replace(",",".");
angles.rolling = Math.round(roll);
angles.pitching = Math.round(pitch);
tvX.setText(roll_print);
tvY.setText(pitch_print);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public static byte[] intToByteArray(int intValue, int intValue1) {
ByteBuffer b = ByteBuffer.allocate(8);
//b.order(ByteOrder..BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(intValue);
b.putInt(intValue1);
byte[] result = b.array();
//for test
int testnum= bytesToInt(result);
System.out.println("reverse value is="+testnum);
return result;}
private static int bytesToInt(byte[] intBytes){
ByteBuffer bb = ByteBuffer.wrap(intBytes);
return bb.getInt();}
public byte[] reverseArray(byte[] arr)
{
int left = 0;
int right = arr.length - 1;
while (left < right) {
byte temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;}
}
我知道這文章。但是我正在用UDP連接尋找東西,並從另一個線程讀取傳感器數據。 – user3844748 2014-09-18 20:33:10