在Service中弹出Toast和Dialog

Posted Cloud_Castle

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Service中弹出Toast和Dialog相关的知识,希望对你有一定的参考价值。

众所周知,Toast必须在UI主线程上才能正常显示,而在Service中是无法获得Acivity的Context的,在service中想显示出Toast只需将show的消息发送给主线程Looper就可以了


Handler handler = new Handler(Looper.getMainLooper());  
            handler.post(new Runnable()   
                public void run()   
                    Toast.makeText(getApplicationContext(), "存Service is runing!",  
                            Toast.LENGTH_SHORT).show();  
                  
            );  

此时便可显示Toast


Dialog的用法与此类似,但是要多加个权限

在manifest中添加此权限以弹出dialog

<uses-permission Android:name="android.permission.SYSTEM_ALERT_WINDOW" />


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

来自:http://blog.csdn.net/nmzkchina/article/details/15506373


以上是关于在Service中弹出Toast和Dialog的主要内容,如果未能解决你的问题,请参考以下文章

Android在Service中弹出对话框二

Jquery EasyUI的Dialog 怎么在iframe中弹出和不在iframe中弹出一样在窗口最顶层?

android中service显示dialog

Android中弹出dialog后无法捕捉back键

service里面弹出对话框

service里面弹出对话框