【发布时间】:2013-12-09 18:54:52
【问题描述】:
如下图所示。每当我将屏幕更改为 B 类时,我希望 A 类中的后台活动(来自蓝牙的流数据)位置始终运行。UI 仅更新屏幕活动的位置,但使用始终运行的相同后台活动。
我知道在 Android 上只允许运行一项活动活动。这就是我尝试使用 A 类上的 textview UI 更新中的共享首选项传递数据的方式,并尝试在 B 类中获取它。但是,当我将屏幕更改为 B 类时,后台活动停止工作。所以,我之前设置的共享首选项只传递了最后一个数据。
代码如下: 获取数据,A类
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;
}
};
};
接收数据类B
package com.oding.skripsibluetooth3;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
public class Datalog extends Activity{
TextView tvDatalog;
@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");
}
}
我很欣赏任何想法, 我发现有人已经遇到了similar situation。我试图像解决方案所述的那样将静态变量放在变量 sbprint 上,并且有红色警告说“变量 sbprint 的非法修饰符;只允许使用 final” 对于我遇到的特定问题,哪一种更简单?共享首选项?静态变量?还是什么?我该如何解决这个问题? 谢谢你
【问题讨论】:
-
看最后一条评论,这和以前有区别的问题
标签: android sharedpreferences handler background-process