我正在使用通过蓝牙连接的传感器发送有关心率,心跳次数,距离,速度和步幅的信息。
我已经完成了它,它向我显示了有关这5个事实的信息,但我不知道如何保存它们。传感器经常发送信息,大约每秒1次。
我必须在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);
}
}
}
有人知道怎么做吗?
答案 0 :(得分:0)
嗯,你必须做的步骤很少:
覆盖#onCreate方法 - 您将执行sql请求来创建数据库。我建议将用于存储上述数据的列的键名称移动为静态ariables,例如:
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.添加方法以插入您的数据并在每次需要将数据保存到db时调用:
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