文章目录

今天考完试了,早就想更新了,放一个最近写的sensor的小demo。

##sensor-sample
最近老板想让我采集传感器数据和GPS信息,然后考虑通过滤波改善GPS精度。本文只实现了数据的采集和保存,滤波尚在离线实验阶段。

###xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >


<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:ems="10"
android:hint="Enter File Name here..." >


<requestFocus />
</EditText>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Start" />


<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Stop" />


<TextView
android:id="@+id/tv_gps"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp" />


</LinearLayout>

###Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package com.example.sensor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener {

TextView gpsData;
EditText txtData;
Button start;
Button stop;

File file;
FileOutputStream fos;
OutputStreamWriter osw;
BufferedWriter bw;
PrintWriter pw;

private SensorManager sensorManager;
private LocationManager locationManager;
private long currentTime;
private long startTime;

float[] acc = new float[3];
float[] gyro = new float[3];
float[] mag = new float[3];
float[] gps = new float[3];

boolean stopFlag = false;
boolean startFlag = false;
boolean isFirstSet = true;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// show the gps info
gpsData = (TextView) findViewById(R.id.tv_gps);

// file name to be entered
txtData = (EditText) findViewById(R.id.editText1);

// start button
start = (Button) findViewById(R.id.button1);
start.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// start recording the sensor data
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
try {
file = new File(Environment
.getExternalStorageDirectory().getPath(),
txtData.getText() + ".txt");
file.createNewFile();

fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
pw = new PrintWriter(bw);

Toast.makeText(getBaseContext(),
"Start recording the data set",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} finally {
startFlag = true;
}
}
}
});

// stop button
stop = (Button) findViewById(R.id.button2);
stop.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// stop recording the sensor data
try {
stopFlag = true;
Toast.makeText(getBaseContext(),
"Done recording the data set", Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});

sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateView(location);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 8, new LocationListener() {

@Override
public void onStatusChanged(String provider, int status,
Bundle extras)
{

// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
updateView(locationManager
.getLastKnownLocation(provider));
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub

}
});
}

private void updateView(Location location) {
// TODO Auto-generated method stub
if (location != null) {
StringBuilder str = new StringBuilder();
str.append("实时位置信息:\n");
str.append("经度:");
str.append(location.getLongitude());
str.append("\n纬度:");
str.append(location.getLatitude());
str.append("\n高度:");
str.append(location.getAltitude());
str.append("\n速度:");
str.append(location.getSpeed());
str.append("\n方向:");
str.append(location.getBearing());
gps[0] = (float) location.getLongitude();
gps[1] = (float) location.getLatitude();
gps[2] = (float) location.getAltitude();
gpsData.setText(str);
} else {
gpsData.setText("There is no available gps data for now");
}

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onSensorChanged(SensorEvent event) {
if (startFlag) {
if( event.sensor.getType() == Sensor.TYPE_ACCELEROMETER ){
acc[0] = event.values[0];
acc[1] = event.values[1];
acc[2] = event.values[2];
}

if( event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
gyro[0] = event.values[0];
gyro[1] = event.values[1];
gyro[2] = event.values[2];
}

if( event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mag[0] = event.values[0];
mag[1] = event.values[1];
mag[2] = event.values[2];
}

if (isFirstSet) {
startTime = System.currentTimeMillis();
isFirstSet = false;
}

currentTime = System.currentTimeMillis();

for (int i = 0; i < 1; i++) {
if (!stopFlag) {
save();
}

else {
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

private void save() {

pw.write(currentTime - startTime + " " + acc[0] + " " + acc[1] + " "
+ acc[2] + " " + gyro[0] + " " + gyro[1] + " " + gyro[2] + " "
+ mag[0] + " " + mag[1] + " " + mag[2] + gps[0] + " " + gps[1]
+ " " + gps[2] + "\n");
}

@Override
protected void onResume() {
super.onResume();
// register this class as a listener for the sensors
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
}

@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub

}
}

由于demo需要获取位置信息和对外部存储读写权限,需要在Manifest文件中添加以下语句

1
2
3
4
<uses-permission android:name="android.permission.LOCATION_HARDWARE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

文章目录