在普及定位课程中遇到过类似的情况。
这是我们所做的:
文件编写器
写入文件部分对我们来说不是问题,因为我们只收集 GPS 位置而不是其他传感器数据。对我们来说,像下面这样的实现就足够了。不清楚是否必须将数据写入同一个文件,如果没有,那么您应该可以直接使用它。
public class FileOutputWriter {
private static String pathString = "";
private static String sensorString = "";
public static void setPath(Context context, String path) {
pathString = path;
File pathFile = new File(pathString);
pathFile.mkdirs();
}
public static void writeData(String data, String sensor, boolean append) {
File file = new File(pathString + "/" + sensor+ ".log");
long timeStamp = System.currentTimeMillis();
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file, append));
out.write(timeStamp + ":" + data);
out.newLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上传者
为了将数据上传到服务器,我们创建了一个 LogEntries 提示(将其更改为您自己的数据持有者对象或简单的字符串)。
public class DataLogger {
static Vector<LogEntry> log = new Vector<LogEntry>();
public static void addEnty(LogEntry entry) {
Log.d("DEBUG", entry.getStrategy() + " added position to logger " + entry.getLocation());
log.add(entry);
}
public static Vector<LogEntry> getLog() {
return log;
}
public static void clear() {
log.clear();
}
}
注意 Vector 是线程安全的。
最后我们实现了一个 UploaderThread,负责定期检查 DataLogger cue 并上传添加的条目。
public class UploaderThread extends Thread {
public static LinkedList<String> serverLog = new LinkedList<String>();
Boolean stop = false;
Context c;
public UploaderThread(Context c) {
this.c = c;
}
public void pleaseStop() {
stop = true;
}
@Override
public void run() {
while(!stop) {
try {
if(DataLogger.log.size() > 0 && Device.isOnline(c)) {
while(DataLogger.log.size() > 0) {
LogEntry logEntry = DataLogger.getLog().get(0);
String result = upload(logEntry);
serverLog.add("("+DataLogger.log.size()+")"+"ServerResponse: "+result);
if(result != null && result.equals("OK")) {
DataLogger.getLog().remove(0);
} else {
Thread.sleep(1000);
}
}
} else {
serverLog.add("Queue size = ("+DataLogger.log.size()+") + deviceIsonline: "+Device.isOnline(c));
}
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private String upload(LogEntry entry) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yoururl/commit.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tracename",sessionName +"-"+ entry.getStrategy().toString()));
nameValuePairs.add(new BasicNameValuePair("latitude", Double.toString(entry.getLocation().getLatitude())));
nameValuePairs.add(new BasicNameValuePair("longitude", Double.toString(entry.getLocation().getLongitude())));
nameValuePairs.add(new BasicNameValuePair("timestamp", Long.toString(entry.getTimestamp())));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if(response != null) {
InputStream in = response.getEntity().getContent();
String responseContent = inputStreamToString(in);
return responseContent;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String inputStreamToString(InputStream is) throws IOException {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
return total.toString();
}
}
线程只是在您应用的第一个活动中启动:
UploaderThread ut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileOutputWriter.setPath(this, Environment.getExternalStorageDirectory()
.getAbsolutePath());
ut = new UploaderThread(this);
ut.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
ut.pleaseStop();
}
希望这能让你上路