1
無論何時寫入數據,我都需要從USB串口接收數據。在android的後臺服務中運行監聽器
爲此我創建了一個服務,它具有一個當數據可用時從串口讀取數據的監聽器。
我在我的活動中追加了接收到的數據的文本視圖。但我什麼都看不到。
我的服務正在運行但無法接收任何數據。
以下是我的服務類代碼。
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.example.flowtest.displayevent";
private final Handler handler = new Handler();
// DatabaseHandle db = new DatabaseHandle(this);
Intent intent;
int counter = 0;
int i = 0, flag = 0;
String d = "a";
byte[] buf = new byte[5];
byte[] start = new byte[21];
byte[] rbuf;// updated
String str;
Physicaloid mPhysicaloid = new Physicaloid(this);
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
// mPhysicaloid.open();
}
@Override
public void onStart(Intent intent, int startId) {
mPhysicaloid.open();
handler.removeCallbacks(getdata);
handler.post(getdata);
}
private Runnable getdata = new Runnable() {
public void run() {
Log.d("service", "in service");
mPhysicaloid.addReadListener(new ReadLisener() {
@Override
public void onRead(int size) {
// TODO Auto-generated method stub
byte[] rbuf = new byte[size];
mPhysicaloid.read(rbuf, size);
try {
str = new String(rbuf, "UTF-8");
if (str.equals(null)) {
flag = 0;
intent.putExtra("inputString", "no luck");
sendBroadcast(intent);
} else {
flag = 1;
intent.putExtra("inputString", str);
sendBroadcast(intent);
}
// sendBroadcast(intent);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
現在我的活動,
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
private void updateUI(Intent intent) {
// TODO Auto-generated method stub
String data = intent.getStringExtra("inputString").toString();
if(data.equals("NORMAL")){
i = new Intent(MainActivity.this,ModeScreenActivity.class);
startActivity(i);
finish();
}
else{
}
tvAppend(tv1,data);
}
};
請幫我一把。我想使用後臺服務,因爲串行數據將被許多活動使用,並且我不想在所有活動中編寫聽讀者。請幫忙 –
我已經嘗試過不同的可能的方式在互聯網上,但我仍然堅持這個問題 –
你應該追求與「物理化學」的提供者首先。 –