显示土司从目前的服务活动 [英] Show toast at current Activity from service

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

问题描述

我需要显示吐司在目前的活动,如果它出现一些修正方面的服务。因此,服务呼叫服务器,如果是一些修正方面,我要不要介意在此活动他notificate用户。我试图实现这样的:

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

但不知道如何从组件名获得上下文对象。

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

推荐答案

尝试使用一个处理程序。事情大概是干杯,你必须在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天全站免登陆