且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当应用程序在后台时如何显示类似弹出通知的whatsapp?

更新时间:2022-12-27 11:04:50

您可以使用 SYSTEM_ALERT_WINDOW 会显示一个对话框窗口,该对话框窗口将显示在所有其他应用程序的顶部.

You can use SYSTEM_ALERT_WINDOW from your BroadcastReceiver to show one dialog window , which will be shown on top of all other apps.

首先添加权限

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

在清单中,然后在您的 onReceiver 中,如下创建一个AlertDialog

in Manifest , then in your onReceiver , Create one AlertDialog as follows

@Override
public void onReceive(final Context context, Intent intent) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context.getApplicationContext());
        LayoutInflater inflater = LayoutInflater.from(context);
        View dialogView = inflater.inflate(R.layout.your_dialog_layout, null);
        builder.setView(dialogView);
        final AlertDialog alert = builder.create();
        alert.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        alert.show();
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = alert.getWindow();
        lp.copyFrom(window.getAttributes());
        //This makes the dialog take up the full width
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
}