Aide学程序员Android开发

Android 全局对话框使用

2020-01-08  本文已影响0人  Mingho96

前言

最近接到个项目,其中有个小功能,单点登录;同一个账号在一个设备登录后,另一个设备就下线。当应用运行于后台时,我们就需要一个全局的对话框。

开始

AndroidMenifest.xml中加入权限:

 <!--全局对话框,不依附于程序的activity-->
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

对话框配置:

package com.mingho.gsondemo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

/**
 * Author by Mingho,  Date on 2020/1/8.
 * PS: Not easy to write code, please indicate.
 */
class CustomerDialog {
    static void show(final Context context, String msg){
        AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setPositiveButton("去查看", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent=new Intent(context,MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });
        Dialog dialog=builder.create();

        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams attributes = window.getAttributes();
            if (attributes != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    attributes.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
                } else {
                    attributes.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
                }
            }
            window.setAttributes(attributes);
        }
        dialog.show();
    }
}

核心逻辑就是这部分,在调用show()之前设置它的属性:

Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams attributes = window.getAttributes();
            if (attributes != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    attributes.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
                } else {
                    attributes.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
                }
            }
            window.setAttributes(attributes);
        }

使用

 CustomerDialog.show(MainActivity.this,"你有一条新订单");

结语

希望能帮到有缘人

上一篇 下一篇

猜你喜欢

热点阅读