无法解析方法创建,Android MediaPlayer

时间:2015-04-13 14:19:31

标签: android android-mediaplayer

当我通过AlaramManager收到闹钟时,我试图播放声音,所以在我的 BroadcastReceiver,在onReceive我调用我的函数播放声音。唯一的问题是我无法创建媒体播放器,它会引发cannot resolve method create错误。

public class AlarmReceiver extends BroadcastReceiver{
    private MediaPlayer mp;



    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        PowerManager.WakeLock w1 = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK),"");
        w1.acquire();
        //playSound();
        w1.release();
    }


    public void playSound(){
        mp = MediaPlayer.create(AlarmReceiver.this,R.raw.sound);
    }
}

我也尝试在OnReceive中创建媒体播放器,如下所示:mp = MediaPlayer.create(context.this,R.raw.sound);

但那也没有用。

1 个答案:

答案 0 :(得分:0)

MediaPlayer.create()需要Context作为第一个参数。传递当前活动,它应该可以工作。

public class AlarmReceiver extends BroadcastReceiver{
    private MediaPlayer mp;
    private Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        PowerManager.WakeLock w1 = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK),"");
        w1.acquire();
        //playSound();
        w1.release();
    }

    public void playSound(){
        mp = MediaPlayer.create(context, R.raw.sound);
    }
}