【问题标题】:Get the data from sensor and save it somewhere从传感器获取数据并将其保存在某处
【发布时间】:2014-09-11 21:12:51
【问题描述】:

我正在使用通过蓝牙连接的传感器发送有关心率、心跳次数、距离、速度和步幅的信息

我已经完成了,它向我显示了有关这 5 个事实的信息,但我不知道如何保存它们。传感器经常发送信息,大约每秒 1 次。 p>

必须用 SQLite 编写 并使用我认为称为“批量插入”的东西插入数据,因为它比每次传感器发送数据时插入更快。因此,数据必须保存在某处,直到批量插入 SQLite。

这是我目前从传感器实时获取数据的代码:

import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;



    public class hxmDemo extends Activity {


        private static final String TAG = "hxmDemo";


        private TextView mTitle;
        private TextView mStatus;

        private String mHxMName = null;
        private String mHxMAddress = null;

        private BluetoothAdapter mBluetoothAdapter = null;


        private HxmService mHxmService = null;

private void connectToHxm() {

    mStatus.setText(R.string.connecting);


    if (mHxmService == null) 
        setupHrm();

    if ( getFirstConnectedHxm() ) {
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mHxMAddress);
        mHxmService.connect(device);    // Attempt to connect to the device
    } else {
        mStatus.setText(R.string.nonePaired);           
    }

}


    private boolean getFirstConnectedHxm() {


        mHxMAddress = null;     
        mHxMName = null;


        BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();


        Set<BluetoothDevice> bondedDevices = mBtAdapter.getBondedDevices();


        if (bondedDevices.size() > 0) {
            for (BluetoothDevice device : bondedDevices) {
                String deviceName = device.getName();
                if ( deviceName.startsWith("HXM") ) {

                    mHxMAddress = device.getAddress();
                    mHxMName = device.getName();
                    Log.d(TAG,"getFirstConnectedHxm() found a device whose name starts with 'HXM', its name is "+mHxMName+" and its address is ++mHxMAddress");
                    break;
                }
            }
        }





        return (mHxMAddress != null);
   }




@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.e(TAG, "onCreate");


    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.rawdata);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);


    mTitle = (TextView) findViewById(R.id.title);
    if ( mTitle == null ) {
        Toast.makeText(this, "Something went very wrong, missing resource, rebuild the application", Toast.LENGTH_LONG).show();
        finish();
    }            


    mStatus = (TextView) findViewById(R.id.status);
    if ( mStatus == null ) {
        Toast.makeText(this, "Something went very wrong, missing resource, rebuild the application", Toast.LENGTH_LONG).show();
        finish();
    }            


    mTitle.setText(R.string.hxmDemoAppName);
    mStatus.setText(R.string.initializing);



mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


Intent intent = new Intent(this, WelcomeMessage.class);
startActivityForResult( intent , 1 );


if (mBluetoothAdapter == null) {

    Toast.makeText(this, "Bluetooth is not available or not enabled", Toast.LENGTH_LONG).show();
    mStatus.setText(R.string.noBluetooth);

 } else {

    if (!mBluetoothAdapter.isEnabled()) {
        mStatus.setText(R.string.btNotEnabled);
        Log.d(TAG, "onStart: Blueooth adapter detected, but it's not enabled");
    } else {
        mStatus.setText(R.string.connecting);
        connectToHxm();


       }
     }        
}


@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart");


    if (mBluetoothAdapter != null ) {
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult     
        if (!mBluetoothAdapter.isEnabled()) {
            mStatus.setText(R.string.btNotEnabled);
            Log.d(TAG, "onStart: Blueooth adapter detected, but it's not enabled");
        }
    } else {
        mStatus.setText(R.string.noBluetooth);
        Log.d(TAG, "onStart: No blueooth adapter detected, it needs to be present and enabled");
    }

}

@Override
public synchronized void onResume() {
    super.onResume();
    Log.d(TAG, "onResume");

    // Performing this check in onResume() covers the case in which BT was
    // not enabled during onStart(), so we were paused to enable it...
    // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
    if (mHxmService != null) {

        if (mHxmService.getState() == R.string.HXM_SERVICE_RESTING) {
          // Start the Bluetooth scale services
          mHxmService.start();
        }
    }
}

private void setupHrm() {
    Log.d(TAG, "setupScale:");

    // Initialize the service to perform bluetooth connections
    mHxmService = new HxmService(this, mHandler);
}

@Override
public synchronized void onPause() {
    super.onPause();
    Log.e(TAG, "- ON PAUSE -");
}

@Override
public void onStop() {
    super.onStop();
    Log.e(TAG, "-- ON STOP --");
}

@Override
public void onDestroy() {
    super.onDestroy();
    // Stop the Bluetooth chat services
    if (mHxmService != null) mHxmService.stop();
    Log.e(TAG, "--- ON DESTROY ---");
}


private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case R.string.HXM_SERVICE_MSG_STATE: 
            Log.d(TAG, "handleMessage():  MESSAGE_STATE_CHANGE: " + msg.arg1);
            switch (msg.arg1) {
                case R.string.HXM_SERVICE_CONNECTED:
                    if ((mStatus != null) && (mHxMName != null)) {
                        mStatus.setText(R.string.connectedTo);
                        mStatus.append(mHxMName);
                    }
                    break;

                case R.string.HXM_SERVICE_CONNECTING:
                    mStatus.setText(R.string.connecting);
                    break;

                case R.string.HXM_SERVICE_RESTING:
                    if (mStatus != null ) {
                        mStatus.setText(R.string.notConnected);
                    }
                    break;
            }
            break;

        case R.string.HXM_SERVICE_MSG_READ: {

            byte[] readBuf = (byte[]) msg.obj;
            HrmReading hrm = new HrmReading( readBuf );
            hrm.displayRaw();
            break;
        }

        case R.string.HXM_SERVICE_MSG_TOAST:
            Toast.makeText(getApplicationContext(), msg.getData().getString(null),Toast.LENGTH_SHORT).show();
            break;
        }
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.option_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        case R.id.scan:
            connectToHxm();
            return true;

        case R.id.quit:
            finish();
            return true;

        case R.id.about: {
            /*
             * Start the activity that displays our welcome message
             */
            Intent intent = new Intent(this, WelcomeMessage.class);
            startActivityForResult( intent , 1 );
            break;
        }
    }

    return false;
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult " + requestCode);

    switch(requestCode)
    {  

        case 1:
            break;

    }             
}

public class HrmReading {
    public final int STX = 0x02;
    public final int MSGID = 0x26;
    public final int DLC = 55;
    public final int ETX = 0x03;

    private static final String TAG = "HrmReading";


    int heartRate;
    int heartBeatNumber;

    long distance;
    long speed;
    byte strides;    

    public HrmReading (byte[] buffer) {
        int bufferIndex = 0;

        Log.d ( TAG, "HrmReading being built from byte buffer");

        try {

            heartRate           = (int)(0x000000FF & (int)(buffer[bufferIndex++]));
            heartBeatNumber     = (int)(0x000000FF & (int)(buffer[bufferIndex++]));
            distance            = (long) (int)((0x000000FF & (int)buffer[bufferIndex++]) | (int)(0x000000FF & (int)buffer[bufferIndex++])<< 8);
            speed               = (long) (int)((0x000000FF & (int)buffer[bufferIndex++]) | (int)(0x000000FF & (int)buffer[bufferIndex++])<< 8);
            strides             = buffer[bufferIndex++];

        } catch (Exception e) {
            /*
             * An exception should only happen if the buffer is too short and we walk off the end of the bytes,
             * because of the way we read the bytes from the device this should never happen, but just in case
             * we'll catch the exception
             */
            Log.d(TAG, "Failure building HrmReading from byte buffer, probably an incopmplete or corrupted buffer");
        }


        Log.d(TAG, "Building HrmReading from byte buffer complete, consumed " + bufferIndex + " bytes in the process");

        dump();
        }



        private void displayRaw() {       

            display ( R.id.heartRate, (int)heartRate );
            display ( R.id.heartBeatNumber,  (int)heartBeatNumber );
            display ( R.id.distance,   distance );
            display ( R.id.speed,   speed );
            display ( R.id.strides,  (int)strides );

        }    

    public void dump() {

            Log.d(TAG,"...heartRate "+ ( heartRate ));
            Log.d(TAG,"...heartBeatNumber "+ ( heartBeatNumber ));
            Log.d(TAG,"...distance "+ (  distance ));
            Log.d(TAG,"...speed "+ (  speed ));
            Log.d(TAG,"...strides "+ ( strides ));

    }    


    private void display  ( int nField, int d ) {   
        String INT_FORMAT = "%d";

        String s = String.format(INT_FORMAT, d);

        display( nField, s  );
    }


    private void display  ( int nField, long d ) {   
        String INT_FORMAT = "%d";

        String s = String.format(INT_FORMAT, d);

        display( nField, s  );
    }


    private void display ( int nField, CharSequence  str  ) {
        TextView tvw = (TextView) findViewById(nField);
        if ( tvw != null )
            tvw.setText(str);
        }
    }          
}

有人知道怎么做吗?

【问题讨论】:

    标签: android sqlite bluetooth


    【解决方案1】:

    嗯,有几个步骤,你必须做:

    1. 通过扩展#SQLiteOpenHelper 创建您自己的类 - 它将帮助您处理您的数据库
    2. 覆盖 #onCreate 方法 - 您将执行 sql 请求来创建数据库。我建议移动将上述数据存储为静态变量的列的键名,例如:

      public static final class db {
      
        public static final String DATABASE_TABLE = "data_table";
      
        public static final String KEY_ID = "id";
        public static final String KEY_HEART_RATE = "heart_rate";
        public static final String KEY_HEART_BEAT_NUMBER = "heart_beat_number";
        public static final String KEY_DISTANCE = "distance";
        public static final String KEY_SPEED = "speed";
        public static final String KEY_STRIDER = "strides";
      
        public static final String CREATE_DATA_TABLE =
        "CREATE TABLE " + DATABASE_TABLE + " (" 
          + KEY_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " 
          + KEY_HEART_RATE + " TEXT NOT NULL, " 
          + KEY_HEART_BEAT_NUMBER + " TEXT NOT NULL, " 
          + KEY_DISTANCE + " TEXT NOT NULL, " 
          + KEY_SPEED + " TEXT NOT NULL, " 
          + KEY_STRIDER + " TEXT NOT NULL");
      

    而#onCreate 可能看起来像这样:

    @Override
    public void onCreate(SQLiteDatabase db) {
      try {
        db.execSQL(CSConfig.db.db.CREATE_DATA_TABLE);
      } catch (SQLiteException e) {
        //Can not create table:
      }
    }
    

    3.添加方法来插入你的数据并在每次需要将数据保存到数据库时调用:

         public final void insertNewData(String heartRate, String heartBeatNumber, String distance, String speed, String stider, ) {
    
           ContentValues dataRowValues = new ContentValues();
           dataRowValues.put(CSConfig.db.db.KEY_HEART_RATE, heartRate);
           dataRowValues.put(CSConfig.db.db.KEY_HEART_BEAT_NUMBER, heartBeatNumber);
           dataRowValues.put(CSConfig.db.db.KEY_DISTANCE, distance);
           dataRowValues.put(CSConfig.db.db.KEY_SPEED, speed);
           dataRowValues.put(CSConfig.db.db.KEY_STRIDER, strider);
    
           insert(CSConfig.db.db.DATABASE_TABLE, null, dataRowValues);
         }
    

    PS。我省略了有关打开数据库访问的详细信息。您可以找到更多详细信息,例如here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-15
      • 2022-01-15
      • 2020-09-19
      • 1970-01-01
      • 2018-12-06
      • 2021-10-21
      • 2020-03-03
      • 2021-05-15
      相关资源
      最近更新 更多