RayCharles
RayCharles

Reputation: 19

Calling an activity from another class - Android

How to call an activity from another class to a non-Activity class?

My code is as follows (Activity Class)

public void onCreate(Bundle savedInstanceState){super.onCreateSavedInstanceState);
 this.mp();
    }
public MediaPlayer mp(){//insert method here// }

Then in my non activity class i call

Intent i = new Intent();


    i.setClassName(".......process", ".....ActualRenderingMedia");
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);

however if I try to use context.startActivity it will give an error asking me to create the activity method. I can't use getApplicationContext.startActivity either.

Upvotes: 1

Views: 1216

Answers (1)

Phil
Phil

Reputation: 36289

Is your non-Activity class instantiable? If so, you can add a constructor to the class that accepts a Context Object, and instantiate it from your main Activity.

For example, in you non-Activity class:

public class MyClass {
    Context context;
    public MyClass(Context context) {
        this.context = context;
    }
    public void someOtherMethod() {
       Intent i = new Intent(...);
       context.startActivity(i);
    }
}

And in your main Activity:

MyClass myclass = new MyClass(this);
...
myclass.someOtherMethod();

Upvotes: 2

Related Questions