上下文未被识别:方法不适用于参数 [英] Context not recognisied:Method not applicable for arguments

查看:300
本文介绍了上下文未被识别:方法不适用于参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图让一个定时器在我的Android应用程序中每1.5秒播放MP3文件(哔声)。我有以下代码并收到错误MediaPlayer类中的方法create(context,int)不适用于我的运行函数中的参数(Beep.RemindTask,int):

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();

    }
}

我不明白为什么不适用,参数是否相同?我知道它可能与上下文有关,我不太清楚,但是从这里: Android上的上下文是什么?我知道在创建新对象或访问共享共享资源时使用它们。我试过 getApplicationContext() getContext() getBaseContext()但仍然收到错误。我相信哔哔声对象所需要的一切都在这个上下文中。任何建议或想法?

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?

推荐答案

你的课是一个非活动类,所以你不能直接得到一个上下文。当您从活动中实例化Beep的实例时,请在构建器中传入活动的上下文。

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.

将一个变量添加到您的Beep类以保存上下文:

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

private Context context;

在构造函数中存储:

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

然后你可以这样做:

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

这篇关于上下文未被识别:方法不适用于参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆