前言
最近接到個(gè)項(xiàng)目诱咏,其中有個(gè)小功能,單點(diǎn)登錄袋狞;同一個(gè)賬號(hào)在一個(gè)設(shè)備登錄后,另一個(gè)設(shè)備就下線醇疼。當(dāng)應(yīng)用運(yùn)行于后臺(tái)時(shí),我們就需要一個(gè)全局的對話框秧荆。
開始
AndroidMenifest.xml中加入權(quán)限:
<!--全局對話框,不依附于程序的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();
}
}
核心邏輯就是這部分,在調(diào)用show()之前設(shè)置它的屬性:
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,"你有一條新訂單");
結(jié)語
希望能幫到有緣人