【问题标题】:Showing a Toast notification from a service [duplicate]显示来自服务的 Toast 通知 [重复]
【发布时间】:2016-07-07 06:59:32
【问题描述】:

我有一个监控前台应用程序的后台服务。它用于保护某个应用程序,如果受保护的应用程序位于前台,然后由于另一个应用程序启动而被推送到后台,它将向用户显示另一个应用程序已接管为前台应用程序的通知。

我能够检测到开关,但有没有办法在检测后显示 Toast 通知/AlertDialog 以提醒服务中的用户?

【问题讨论】:

  • 在服务中显示警报对话框是个坏主意。您需要活动上下文来显示这一点。所以从服务导航到活动并显示警报对话框
  • 好的,如果我不采用 AlertDialog 方式,Toast 或其他形式的通知怎么样?请注意,接管前台应用程序的 Activity 不属于我。它可能劫持了我的 Activity

标签: android android-service android-notifications android-alertdialog toast


【解决方案1】:

您可以在Service 类中获取应用程序基础上下文,并使用Handler 显示祝酒词。

private Context appContext;

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        appContext = getBaseContext();        //Get the context here
    }

    //Use this method to show toast
    void showToast(){
        if(null != appContext){
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() 
            {
               Toast.makeText(appContext, "Printing Toast Message", Toast.LENGTH_SHORT).show();
            }

        });

        }
    }

【讨论】:

  • 你试过了吗?我不认为它会起作用
  • 我在上一个项目中使用过这个。它有效:)
  • 对话框呢?
  • 根据他的问题/要求 Toast OR Dialog。这适用于吐司。我没有尝试过对话
  • 谢谢。这非常适合 Toast。我实际上并不需要 AlertDialog,只需要一种通知用户的方式。 Toast 现在工作得很好。再次感谢!
【解决方案2】:

你可以使用 Handler 来获取 main looper。试试下面的片段

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable(){
@Override
public void run(){
 Toast.makeText(YourServiceName.this,"your   message",Toast.LENGHT_SHORT).show();
 }
});

【讨论】:

    【解决方案3】:

    这样试试

    final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                     Toast.makeText(getBaseContext(), "TEST", Toast.LENGTH_SHORT).show();
    
                   handler.postDelayed(this, 1000);
                    }
                },1000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 2020-06-13
      • 2015-11-19
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多