Service中创建Dialog对话框

xiaoxiao2021-02-28  69

Android Service中创建Dialog对话框

一般我们都是在Activity中创建Dialog的,无论是系统的AlertDialog还是我们自定义的Dialog。 我们只需设置title,message等信息,然后show出来即可

可是在Service中呢,没有Activity,Dialog没有了依赖,那么怎么办呢? 这时,Dialog就要以系统对话框的形式弹出了。在我们取得Dialog对象后,需给它设置类型,即

mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

同时,必须提供系统弹框对应的权限:

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

注:小米手机等高度自定义的手机,可能还需要手动设置显示悬浮窗的权限。。。(恶心人。。。)

看看官方解释吧:

/** * Window type: system window, such as low power alert. These windows * are always on top of application windows. * In multiuser systems shows only on the owning user's window. */ public static final int TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3;

随手一段原始代码来证明自己吧。。。

private void createDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("title") .setMessage("content") .setNegativeButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); Dialog dialog = builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); }

完…


转载请注明原文地址: https://www.6miu.com/read-2500123.html

最新回复(0)