How to raise an alert dialog from BroadcastReceiver class?

前端 未结 3 853
孤街浪徒
孤街浪徒 2020-12-18 08:29

I have used a timer method in an Activity class. In that method I have an intent from Activity class to a BroadcastReceiver class.

3条回答
  •  生来不讨喜
    2020-12-18 09:14

    1) In Activity:

    public static Context ctx;
    
    onCreate {
        ctx = this;
    }
    
    public void showAlertDialog(Context context, String title, String message) {
    
        final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        // Setting Dialog Title
        alertDialog.setTitle(title);
    
        // Setting Dialog Message
        alertDialog.setMessage(message);
    
        // Setting OK Button
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Okay",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) 
            {
                alertDialog.dismiss();
            }
        });
    
        // Showing Alert Message
        alertDialog.show();
    }
    

    2) In BroadcastReceiver.onReceive:

    YourActivity ac= new YourActivity ();
    ac.showAlertDialog(YourActivity.ctx, "test", "test");
    

提交回复
热议问题