Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

java - Context not recognisied:Method not applicable for arguments

I'm trying to make a timer to play an MP3 file every 1.5 seconds(a beep) in my android application. I have the following code and receive the error "The method create (context,int) in the type MediaPlayer is not applicable for the arguments (Beep.RemindTask,int)" in my run function below:

package com.example.timer;

import java.util.Timer;
import java.util.TimerTask;
import android.media.AudioManager;
import android.media.MediaPlayer;

public class Beep {

 Timer timer;

    public Beep() {

        timer = new Timer();
        timer.schedule(new RemindTask(),
                   0,        //initial delay
                   1*1500);  //subsequent rate
    }

    class RemindTask extends TimerTask {



        public void run() {

            MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.beep); 
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.start();


        }
    }

    public void main(String args[]) {

        new Beep();

    }
}

I don't understand why it isn't applicable, the parameters being the same? I know its probably something to do with the context, which I am not entirely sure of, but from here: What is 'Context' on Android? I know they are used when creating new objects or accessing shared common resources. I have tried getApplicationContext(),getContext() and getBaseContext() but still receive errors. I believe that everything needed by the beep object to operate is located in this context. Any suggestions or ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your class is a non-activity class so you can't directly get at a context. When you instantiate an instance of Beep from your activity, pass in the activity's context in the constuctor.

Add a variable to your Beep class to hold a context:

private Context context;

In the constructor, store it:

public Beep(Context context) {
this.context=context;
//the rest of your constructor code...
}

Then you can do this:

MediaPlayer mPlayer = MediaPlayer.create(context, R.raw.beep);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...