我想在收到消息时播放声音。我有一个 BroadcastReceiver,我在其中调用另一个名为 play 的函数来播放声音或音乐。我的代码如下所示:
在我的主要活动中
我的游戏活动:
public class PlayActivity extends Activity
{
private MediaPlayer mediaPlayer;
public void play() {
mediaPlayer = MediaPlayer.create(this, R.raw.gotye);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
我的广播接收器看起来像:
package org.secure.sms;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver
{
public static final String SMS_EXTRA_NAME = "pdus";
public static final String SMS_URI = "content://sms";
private MediaPlayer mediaPlayer;
private MainActivity Play;
public void onReceive( Context context, Intent intent )
{
// Get SMS map from Intent
Bundle extras = intent.getExtras();
String messages = "";
if ( extras != null )
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
// Get ContentResolver object for pushing encrypted SMS to incoming folder
ContentResolver contentResolver = context.getContentResolver();
for ( int i = 0; i < smsExtra.length; ++i )
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
putSmsToDatabase( contentResolver, sms );
}
// Display SMS message
Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
Play.play();
}
}
我收到一条错误消息,说应用程序不幸失败了。我可以看到 toast 消息,但应用程序没有播放音乐。