我的Android應用程序使用線程來偵聽來自通過USB連接的PC的套接字連接。在PC打開連接(響應某些用戶驅動事件)之後的某個時刻,我想通過它發送一些數據。如何保持連接線程活着? (我需要使用守護進程嗎?)
public void onCreate(Bundle savedInstanceState) {
// SNIP: stuff and nonsense
connection = new Thread(new ServerThread());
connection.start();
}
public boolean onTouchEvent(MotionEvent event) {
// SNIP: decide what to do; create string 'coordString'
Message coordMsg = coordHandler.obtainMessage();
Bundle coordMsgData = new Bundle();
coordMsgData.putString("coords", coordString);
coordMsg.setData(coordMsgData);
if(coordHandler!=null)
{
coordHandler.sendMessage(coordMsg);
}
return false;
}
public class ServerThread extends Thread
{
public void run() {
this.setName("serverThread");
Looper.prepare();
coordHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
Log.v(INNER_TAG,"here");
}
};
// SNIP: Connection logic here
Looper.loop();
}
}.
適用年齡,我抓我的頭不知道爲什麼我從來沒有見過的INNER_TAG
值出現在我的日誌後,觸摸事件。我可以使用日誌調試追蹤執行到coordHandler!=null
區塊,但處理程序似乎從未觸發。
然後它讓我感到震驚:線程可能在完成連接後退出。 呃!不太清楚我以前發生的事情,但我會責怪它,Loop
做了一件神奇的事情。
所以我的問題是:我如何讓我的線程運行?官方Android dev reference on threads簡要提及
一個線程也可以做一個守護進程,它使它在後臺運行。
這自然使我的* nix感覺到興奮。 (順便說一句,你有沒有看過新的蜘蛛俠電影呢?這很不錯。)守護神化的答案是什麼?還是我完全失去了情節?
這似乎是要走的路。有沒有可能擴展你的答案來包含一個例子? – 2012-07-12 14:47:43
查看我添加的鏈接 – 2012-07-12 17:00:25