我是Android新手。我正在使用磁传感器数据创建应用程序。我正在关注另一个基于Wifi的程序的源代码。我的基本课程是
public class MainActivity extends AppCompatActivity implements SensorEventListener{
Sensor magnetometer;
SensorManager sm;
public float a,b,c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
getMag(event);
}
}
public static void getMag(SensorEvent event) {
float[] values = event.values;
float x = values[0];
float y = values[1];
float z = values[2];
float value = (float)Math.sqrt(Math.pow(x,2) +Math.pow(y,2) + Math.pow(z,2));
}
@Override
protected void onStop() {
super.onStop();
finish();
}
@Override
protected void onPause() {
super.onPause();
sm.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
我可以用这个访问传感器值,但我想要的是在其他类中使用传感器值。在我关注的源代码中,代码用作。
//this is map activity, here for wifi, it just uses "getScanResult() to scan bssid and value, which can be used in onReciveWifiScanResult
public void onStart() {
super.onStart();
mReceiver = new BroadcastReceiver ()
{
@Override
public void onReceive(Context c, Intent intent)
{
onReceiveWifiScanResults(mWifi.getScanResults());
}
};
}
public void onReceiveWifiScanResults(List<ScanResult> results) {
}
//And the programmer used it in another class to store to the hashmap
public void onReceiveMagScanResults(List<ScanResult> results) {
HashMap<String, Integer> measurements = new HashMap<String, Integer>();
for (ScanResult result : results) {
measurements.put(result.BSSID, result.level);
}
TreeSet<String> keys = new TreeSet<String>();
keys.addAll(measurements.keySet());
keys.addAll(mMeasurements.keySet());
那么,我怎么能从我的主要活动的“onSensorChanged”事件中获取我的磁传感器数据,就像上面的广播接收器一样用来代替“onReceiveWifiscanresult”?
任何帮助都会很棒。谢谢。
答案 0 :(得分:0)
哦,我找到了答案。现在,我可以将数据存储在SQLite数据库中,然后使用游标来访问数据。然后将数据放入hashmap中。
我使用了这段代码
TextView diff= (TextView) findViewById(R.id.calcDiff);
SQLiteDatabase db;
db= openOrCreateDatabase(
"Mag_Positioning.db"
, SQLiteDatabase.CREATE_IF_NECESSARY
, null
);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
Cursor cur = DBHelper.getInstance().getAllData();
cur.moveToFirst();
HashMap<PointF, Float> difference = new HashMap<>();
if (cur.isLast() == false) {
do{
cur1=cur.getInt(2);
cur2=cur.getInt(3);
PointF location = new PointF(cur1, cur2);
z= Float.valueOf(cur.getString(7));
total = Float.valueOf(String.valueOf(Math.sqrt(Math.pow((d-z),2))));
difference.put(location, total);
diff.append("\n" + difference +"\n");
}while(cur.moveToNext());
}
cur.close();
&#13;