在服务的当前活动中显示吐司 [英] Show toast at current Activity from service

查看:18
本文介绍了在服务的当前活动中显示吐司的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果服务有一些更新,我需要在当前活动中显示 Toast.所以服务调用服务器,如果是一些更新,我需要通知用户不管他在哪个活动.我尝试像这样实现它:

I need to show Toast at the current Activity if it come some updatings to the Service. So Service call server and if it is some updatings, I need to notificate user nevermind at which Activity he is. I try to implement it like this:

 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;
    }
}

它不起作用.我还尝试使用

and it doesn't works. I also tried to get current Activity name with

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 中获取上下文对象.

But don't know how to get context object from the ComponentName.

推荐答案


尝试使用处理程序.关于 Toasts 的事情是,您必须在 UI 线程上运行 makeText,服务不运行在该线程上.处理程序允许您发布可在 UI 线程上运行的可运行对象.在这种情况下,您将在 onStartCommand 方法中初始化一个处理程序.


Try using a Handler. Thing about Toasts is, you have to run makeText on the UI thread, which the Service doesn't run on. A Handler allows you to post a runnable to be run on the UI thread. In this case you would initialize a Handler in your onStartCommand method.

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>);
}

这篇关于在服务的当前活动中显示吐司的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆