2012-10-04 111 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