Show toast at current Activity from service

杀马特。学长 韩版系。学妹 提交于 2019-11-28 05:49:13

问题


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

where

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.


回答1:



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


来源:https://stackoverflow.com/questions/12730675/show-toast-at-current-activity-from-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!