简体   繁体   中英

Launch activity from non-activity class

I am trying to launch an ActivityB from an ActivityA via a class.

So I create my non-activity class in an ActivityA, this way:

public class ActivityA extends Activity {
    myDialog = new MyDialog(this);

}

And I launch my second activity in the class constructor as follows :

public MyDialog(Context context) {
    Intent i = new Intent (context, ActivityB.class);
    context.startActivity(i);
}

The problem is I would like to acess MyDialog from ActivityB. Is this possible?

Thanks for helping.

Option 1: You could make your class "MyDialog" static and instead in the constructor, create a void that starts the activityB. I'm not sure why do you want to start activityB from activityB but this work if they are in the same application:

public static class MyDialog {

    public static void StartDialog(Context context){
        System.out.println("STARTING ACTIVITY B");
        Intent i = new Intent (context, ActivityB.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

And in the Activity B use this call:

ActivityA.MyDialog.StartDialog(getApplicationContext());

Option 2: If you don't want to create MyDialog as static, then:

public class MyDialog {

    Context context;

    public MyDialog(Context c){
        context = c;
    }

    public void StartDialog(){
        System.out.println("STARTING ACTIVITY B");
        Intent i = new Intent (context, ActivityB.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

And then, in the ActivityB:

ActivityA ma = new ActivityA();
MyDialog md = ma.new MyDialog(getApplicationContext());
md.StartDialog();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM