在普適定位過程中,情況有些類似。
這是我們所做的事情:
的FileWriter 寫入到文件的部分是不是一個問題,對我們來說,我們只收集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的提示(將其更改爲自己的dataholder對象或簡單字符串)服務器。
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提示並上傳添加的條目。
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();
}
希望這可以讓你在這似乎並沒有回答這個問題,實際的方式
- 當然,一個線程可能是實現的一部分 - 但是沒有一個「應該嘗試做什麼」的問題得到解決 - 只要將「可用數據」觸發寫入後臺線程,對除UI響應之外的其他任何內容的影響都將最小。 –
我應該澄清 - 如果可以避免這種情況,我寧願不要緩衝/排隊寫入10秒 – rsg
@rsg - 如果數據生成速度比I/O處理速度快,那麼某種緩衝是需要(或者你需要願意放棄數據,或者兩者兼而有之)。大約10秒沒有什麼神奇的;據推測數據可以寫得比這更快。但是,您需要處理容量不匹配問題。我在這個答案中加入了一些想法。 –