2013-03-19 56 views
0

我有一個IntentService,它在WindowManager的幫助下創建一個Overlay。在WindowManager中,我添加一個包含ListView的View。現在我想一個新的項目在onHandleIntent方法添加到ListView,但如果我叫從IntentService更新ListView

data.add("String"); 
adapter.notifyDataSetChanged(); 

系統將引發錯誤

Only the original thread that created a view hierarchy can touch its views. 

我能做些什麼來防止這種情況?

+0

看一看[內容提供者(http://developer.android.com/guide/topics/providers/content-providers.html)。他們會幫助你。 – 2013-03-19 17:39:19

+0

在onStart中創建一個處理程序,然後在這個處理程序上發佈消息來更新視圖,如果我正確理解你在做什麼。 – njzk2 2013-03-19 17:46:46

回答

0

您可以通過讓保存ListView的Activity執行更新來解決此問題。 Activity.runOnUiThread()應該做的工作=]

+0

我沒有看到我在哪裏有Activity ...我只有IntentService和Overlay – Cilenco 2013-03-19 17:40:07

1

屏幕可能只能由UI線程更新。服務不能保證它在UI線程中運行。因此,服務可能不會直接更新屏幕。

解決方法是發送消息到UI線程。有很多方法可以做到這一點。這裏是一個:

在的onCreate(),用於連接到屏幕上的活動創建的消息處理程序:

mHandler = new Handler(Looper.getMainLooper()) { 
    @Override 
    public void handleMessage(Message inputMessage) { 
     Update the UI here using data passed in the message. 
    } 
    } 

使mHandler提供給服務(可能通過()中StartService使用的意圖

在服務發送消息到處理程序:

Message msg = mHandler.obtainMessage(...); 
     ... add info to msg as necessary 
    msg.sendToTarget(); 

這些頁面可以與細節幫助:

http://developer.android.com/reference/android/os/Handler.html

http://developer.android.com/reference/android/os/Message.html