How to show Dialog Box from the class which extends Application in android?

前端 未结 3 1670
谎友^
谎友^ 2020-12-17 10:21

I want show a dialog box after specific condition , but for demo right now I want show a Dialog Box from the class which extends Application . here is my code



        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 10:48

    Your program may behave as you want!**

    ** Just remember that you need to think about the consequences of its actions.

    public class MyApplication extends Application {
            /** 
            * show example alertdialog on context -method could be moved to other class 
            * (eg. MyClass) or marked as static & used by MyClas.showAlertDialog(Context)
            * context is obtained via getApplicationContext() 
            */
            public void showAlertDialog(Context context) {
                /** define onClickListener for dialog */
                DialogInterface.OnClickListener listener 
                      = new   DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    // do some stuff eg: context.onCreate(super)
                    }
                };
    
                /** create builder for dialog */
                AlertDialog.Builder builder = new AlertDialog.Builder(context)
                    .setCancelable(false)
                    .setMessage("Messag...")
                    .setTitle("Title")
                    .setPositiveButton("OK", listener);
                /** create dialog & set builder on it */
                Dialog dialog = builder.create();
                /** this required special permission but u can use aplication context */ 
                dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                /** show dialog */
                dialog.show();
            }
    
            @Override
            public void onCreate() {
                showAlertDialog(getApplicationContext());
            }
    }
    

    imports for abowe:

    import android.app.AlertDialog;
    import android.app.Application;
    import android.app.Dialog; 
    import android.content.Context;
    import android.content.DialogInterface; 
    import android.view.WindowManager;
    

    edity:

    You cannot **display an application window/dialog through a Context that is not an Activity or Service. Try passing a valid activity reference

    ** u can use application context to create dialog by adding before call to Dialog.show();

    Dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); 
    
    - but this requires permission:  
    
    
    

    Ref:

    • Dialogs
    • AlertDialog
    • WindowType

提交回复
热议问题