我可以從主活動中將數據顯示保存在屏幕上的變量sbprint中。我從緩衝藍牙數據的後臺活動中獲得的可變sbprint。我想將屏幕上顯示的數據記錄到另一個班級。 問題是我不能使用序列化,因爲數據總是從我的藍牙模塊實時模式流。基於here如何將數據從後臺進程傳遞到另一個活動
我用處理器從數據更新我的UI代碼緩衝 注:我得到的內部處理程序共享偏好(這是內部MainActivity.java)
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
SharedPreferences logPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = logPreferences.edit();
String textLog = txtArduino.getText().toString();
editor.putString("log", textLog);
editor.commit();
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
的H處理程序得到的消息對象基於此命令的藍牙文檔ConnectedThread類,
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
我的問題是,我怎麼使用處理器就像上面傳遞變量sbprint到我的新屏幕的類。
這裏是我如何從另一個數據中接收數據。我從共享偏好得到傳遞變量緩衝區中的數據的建議
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datalog);
tvDatalog = (TextView) findViewById(R.id.tvDatalog);
SharedPreferences logPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String text = logPreferences.getString("log", "null");
tvDatalog.setText(text+"\r\n");
}
注: 我從我的MainActivity數據,但好像我的AsyncTask的作品在我的MainActivity停止的畫面切換到另一個類。我如何讓我的背景活動也適用於這兩個類。我的意思是每當我改變我的屏幕到另一個背景活動始終工作。
我不確定它是否適用於您,但您可以將數據存儲在共享偏好設置中並在應用程序中的任何位置檢索它。不要使用serialisable,因爲它會讓你的應用程序太慢。 – Hesam
是的,我知道這一點。任何關於共享偏好的推薦鏈接? –
最佳參考是Android文檔。請參考以下鏈接:http://developer.android.com/training/basics/data-storage/shared-preferences.html – Hesam