【问题标题】:Android: Send accelerometer data over UDP from threadAndroid:从线程通过 UDP 发送加速度计数据
【发布时间】:2014-09-18 18:39:04
【问题描述】:

我正在尝试使用 MainActivity 和 SensorEventListener 制作应用程序。来自加速度计的数据将保存在结构(类,两个 int 变量)中。 我创建了在应用程序启动后运行的 UDP 客户端线程。 UDP 客户端将这两个变量发送到远程服务器。

问题是我需要知道传感器的数据何时刷新,然后我通过 UDP 客户端(另一个线程)发送它。我是 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;}

}

【问题讨论】:

    标签: java android multithreading android-activity event-listener


    【解决方案1】:

    最好的办法是去官方 google android API 并检查对象文档
    http://developer.android.com/reference/android/hardware/SensorEventListener.html#onSensorChanged(android.hardware.SensorEvent)


    为了获得更多指导,我添加了一些带有教程的很棒的网站(但谷歌也可以很好地为您服务)-
    http://www.vogella.com/tutorials/AndroidSensor/article.html
    http://code.tutsplus.com/tutorials/using-the-accelerometer-on-android--mobile-22125

    【讨论】:

    • 我知道这篇文章。但我正在搜索具有 UDP 连接的东西并从另一个线程读取传感器数据。
    【解决方案2】:

    我在这里找到了解决方案:http://techtej.blogspot.sk/2011/02/android-passing-data-between-main.html

    1. 创建工作线程
    2. 调用 Looper 方法
    3. 创建一个处理程序来接收消息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多