2012-10-04 110 views
2

如果需要更新服務,我需要在當前活動中顯示Toast。因此,服務呼叫服務器,如果它是一些更新,我需要不知道他在哪個活動的用戶。我嘗試實現這樣的:在當前服務中顯示吐司

Toast.makeText(ApplicationMemory.getInstance(), "Your order "+progress+"was updated", 
        Toast.LENGTH_LONG).show(); 

其中

public class ApplicationMemory extends Application{ 
static ApplicationMemory instance; 

    public static ApplicationMemory getInstance(){ 
     return instance; 
    } 
} 

,並沒有工作。我也嘗試獲取當前活動名稱與

ActivityManager am = (ActivityManager) ServiceMessages.this.getSystemService(ACTIVITY_SERVICE); 
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); 
ComponentName componentInfo = taskInfo.get(0).topActivity; 
componentInfo.getPackageName(); 
Log.d("topActivity", "CURRENT Activity ::" + componentInfo.getClassName()); 

但不知道如何從ComponentName中獲取上下文對象。

+0

ComponentName中沒有Context對象。嘗試在Toast.makeText()中使用getApplicationContext()作爲Context。 – DunClickMeBro

+0

試圖做到這一點,但它不顯示 –

回答

12

嘗試使用處理程序。關於Toasts的事情是,你必須在UI線程上運行makeText,該服務不運行。 Handler允許你發佈一個runnable在UI線程上運行。在這種情況下,您將在onStartCommand方法中初始化一個Handler。

private Handler mHandler; 

@Override 
onStartCommand(...) { 
    mHandler = new Handler(); 
} 

private class ToastRunnable implements Runnable { 
    String mText; 

    public ToastRunnable(String text) { 
     mText = text; 
    } 

    @Override 
    public void run(){ 
     Toast.makeText(getApplicationContext(), mText, Toast.LENGTH_SHORT).show(); 
    } 
} 


private void someMethod() { 
    mHandler.post(new ToastRunnable(<putTextHere>); 
} 
+0

非常感謝您的簡單和可行的解決方案!你幫了很多! –

+0

如果服務在不同的線程上運行,您可能必須實例化像new Handler(Looper.getMainLooper())這樣的處理程序。 – Petr

+3

「您必須在UI服務無法運行的UI線程上運行makeText」是錯誤的。 「服務」中的代碼確實在UI線程上運行。 – Trevor