从服务调用的活动Toast的正确上下文?

时间:2012-01-25 10:08:45

标签: android android-service toast

我在主要活动中获得了以下方法

public void showMessages(int MSGCODE) {
    Log.d("MSG", "showmessage reached with code " + MSGCODE);
    switch (MSGCODE) 
    { 
      case '0': 
        Toast.makeText(tabHost.getContext(), "Account verification failed. Please try to reenter your password.", Toast.LENGTH_LONG).show(); 
        break; 
      case '1': 
        Toast.makeText(tabHost.getContext(), "Networking Service started.", Toast.LENGTH_LONG).show();
        break; 
      case '2': 
        Toast.makeText(tabHost.getContext(), "Networking Service stopped.", Toast.LENGTH_LONG).show(); 
        break; 
      case '3': 
        Toast.makeText(tabHost.getContext(), "Connection to server failed.", Toast.LENGTH_LONG).show();
        break; 
    }
}

在服务中,我调用这样的方法:

MAIN_ACTIVITY.showMessages(Consts.CONNECTION_FAILED);

但没有吐司出现。 TabHost托管了三个不同的标签。我已经有了这个想法,它可能是我选择的错误背景,但我并不知道哪一个是正确的,如何得到它。

private TabHost tabHost;
private final String[] loginStrings = new String[2];

public static Boolean runOnce = true;
public static ArrayList<String> messages;
private Intent svc;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tabHost = getTabHost();
    Intent intent = new Intent().setClass(this, BuddylistActivity.class);
    tabHost.addTab(tabHost.newTabSpec("tabBuddylist").setIndicator("Buddylist").setContent(intent));
    intent = new Intent().setClass(this, ChatsActivity.class);
    tabHost.addTab(tabHost.newTabSpec("tabBuddylist").setIndicator("Chats").setContent(intent));
    intent = new Intent().setClass(this, SchedularActivity.class);
    tabHost.addTab(tabHost.newTabSpec("tabBuddylist").setIndicator("Schedular").setContent(intent));

3 个答案:

答案 0 :(得分:2)

尝试将showMessages()设为静态并将Context作为参数传递。

public static void showMessages(Context context, int MSGCODE)

您可以显示像

这样的Toast消息
Toast.makeText(context, "Networking Service started.", Toast.LENGTH_LONG).show();

并从服务中调用此方法,您只需将this作为上下文传递:

MAIN_ACTIVITY.showMessages(this, Consts.CONNECTION_FAILED);

这样即使Activity本身被破坏,你的Toasts也会显示出来。

您可以保留原始(non-static方法)并将其实现为

public void showMessages(int MSGCODE){
     showMessages(this, MSGCODE); //calls static method with current context
}

答案 1 :(得分:0)

应该是

Toast.makeText(getApplicationContext(), "Connection to server failed.", Toast.LENGTH_LONG).show();

答案 2 :(得分:-1)

这是我制作祝酒词的方式,

Toast toast = Toast.makeText(contetx, Message, Duraction);
toast.show(); //This being the part that is missing

我可能完全错了,但我总是使用toast.show()方法实际让它显示