我在Android中使用代码播放声音, 但是,当我在主类中播放声音时,以下代码可以正常工作,
private void playSound() {
MediaPlayer player = MediaPlayer.create(this, R.raw.a);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}}
while,如果我在另一个类中执行此代码,代码会在此行上出错,
MediaPlayer player = MediaPlayer.create(this, R.raw.a);
这是错误,
MediaPlayer类型中的方法create(Context,int)不是 适用于参数(AlarmReceiver,int)
我观察到我的Main Activity
类扩展Activity
而另一个类扩展BroadcastReceiver
,我知道这导致了问题,但我不知道如何解决这个问题?
这是完整的代码,
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
playSound();
}
private void playSound() {
MediaPlayer player = MediaPlayer.create(this, R.raw.a);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}}
我想用什么来代替this
关键字来使其在Main
以外的任何类中都有效?
答案 0 :(得分:2)
您可以将上下文传递给playsound(上下文)
private void playSound(Context mContext) {
MediaPlayer player = MediaPlayer.create(mContext, R.raw.a);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
希望这会有所帮助。
答案 1 :(得分:2)
在onRecieve方法中,您获得Context
作为参数。如果您将Context
传递给playSound()
方法,则可以使用Context
创建MediaPlayer
:
@Override public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message Toast.makeText.
makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
playSound(context); //Pass the context to your playSound method.
}
然后,您需要更新playSound()
方法才能收到Context
:
private void playSound(Context c) {
MediaPlayer player = MediaPlayer.create(c, R.raw.a); //Use the Context c instead of using this.
//the rest of your code...
}