Show dialog alert from a non-activity class in android

后端 未结 7 1983
慢半拍i
慢半拍i 2020-12-06 02:37

I want to show an Alert Dialog via AlertDialogManager class to a non-activity class DeviceAdminReceiverSample\'s method onDisabl

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 03:02

    Here's a quick method of properly performing this task that has done the job for me. Basically, what you would do is just create a new thread.


    1. Declare a public and static variable with a type that matches the original activity class.

      public static Activity1 activity;

    Activity1 is the class that the variable resides in.


    1. Upon calling the method onCreate();, set the variable to be equal to the context of the activity, otherwise known as this.

    Example:

    @Override 
        protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        activity = this;
    }
    


    3. Since we now have the context of the activity, we can use it to create a function with an alert dialog by using the runOnUiThread(); method inside of the function that will call the alert dialog. We would use a new Runnable() for the runnable action required for runOnUiThread();, and to have the alert dialog actually open, we would override the run function of a runnable item and place the code for the alert dialog in there.

    Example function:

    public static void exampleDialog(){
    Activity1.activity.runOnUiThread(new Runnable){
    @Override
        public void run(){
        //alert dialog code goes here.  For the context, use the activity variable from Activity1.
            }
        }
    }
    

    Hope this helps :)

提交回复
热议问题