Android在服务service里使用Toast显示和弹出Dialog

我们一般在Activity里面使用Toast和Dialog,使用比较简单,这里就不用讲了。有时候需要在服务里面使用Toast和Dialog,但是不知道怎么引入上下文Context ,下面介绍另种方式使用Toast和Dialog。

1. Toast在Service中使用 ,直接上代码

Handler handlerThree=new Handler(Looper.getMainLooper());
            handlerThree.post(new Runnable(){
                public void run(){
                    Toast.makeText(getApplicationContext() ,"显示Toast在屏幕上!",Toast.LENGTH_LONG).show();
          }
            });

Toast应该得到主UI的Context才能显示,Google对Toast的说明中,有一句:“A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service,it appears in front of the Activity currently in focus.”
那么按照这句来看,service中创建的toast会在Acivity的UI前面聚焦显示。所以想要toast能够正常工作,需要在Activity的主线程上运行才行,那么如何得到主线程UI的Context呢?可以通过Handler将一个自定义的线程运行于主线程之上。

2. Dialog在Service中使用 ,直接上代码

Builder builder = new AlertDialog.Builder(getApplicationContext())  
                    .setIcon(android.R.drawable.ic_dialog_info)  
                    .setTitle("service中弹出Dialog了")  
                    .setMessage("是否关闭dialog?")  
                    .setPositiveButton("确定",  
                            new DialogInterface.OnClickListener() {  
                                public void onClick(DialogInterface dialog,  
                                        int whichButton) {  

                                }  
                            })  
                    .setNegativeButton("取消",  
                            new DialogInterface.OnClickListener() {  
                                public void onClick(DialogInterface dialog,  
                                        int whichButton) {  

                                }  
                            });  
            final AlertDialog dialog = builder.create();  
            dialog.getWindow().setType(  
                    (WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));  
     Handler handler = new Handler(Looper.getMainLooper());  
     handler.post(new Runnable() {  
                public void run() {  
                    dialog.show();  
                }  
      });  

跟上面的Toast一样,在Service中使用Handler将Dialog运行在主UI线程上。

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值