Reputation: 7571
I have 15 or so activities. Each one of them has a method, and I want to play audio in that method. Now, I have the obvious option to copy and paste the following line of code into each and every one of my activities Now, if I wanted to change something, I would have to go back into each and every one of my activities again. Here is the code:
MediaPlayer pop = MediaPlayer.create(CurrentActivity.this, R.raw.pop);
pop.start();
So, after searching the web for a few hours, I found that most people would just copy and paste it into each activity. So, I put the line of code (above) into a separate java class (which was a service by the way) tried to call that method in the service every time I needed to play the audio. So, I did the following:
public class TwentySeconds extends Service{
public void myPop(View view){
MediaPlayer pop = MediaPlayer.create(TwentySeconds.this, R.raw.pop);
pop.start();
}
}
Now, I got the error non static method cannot be referenced from static context
. So, naturally, I tried to make method myPop
static
. Then, I got the error on TwentySeconds.this
about being referenced from static context. So, it seems I am stuck. Changing the methods to static can't work, as I am trying to use an instance of the class as well using this
. So, how should I go about calling method myPop
where the MediaPlayer
can successfully play?
Thanks for the advice,
Rich
Upvotes: 0
Views: 66
Reputation: 20211
Typically, if a utility method needs a Context
, it is passed in.
public class Utilities {
public static void myPop(Context context){
MediaPlayer pop = MediaPlayer.create(context, R.raw.pop);
pop.start();
}
}
Utilities.myPop(CurrentActivity.this);
Upvotes: 1