当我的应用程序收到短信时,如何播放声音?

时间:2011-06-20 07:54:37

标签: android

我在我的应用程序中使用了BroadcastReceiver类来接收传入的短信,并且在清单文件中对我的应用程序给予高度偏好,以便首先应该由我的应用程序处理传入的消息。

我的主要文件是:

package com.example.demo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;



public class Demo extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) 
{
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();        
    SmsMessage[] msgs = null;
    String str = "";            
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];            
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
            //   str += "SMS from " + msgs[i].getOriginatingAddress();                     
            //  str += " :";
            str += msgs[i].getMessageBody().toString();
            //   str += "\n";        
        }
        //---display the new SMS message---
        //Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        String[] msgText;
        String newstr="";
        msgText=str.split(",");
        newstr+=msgText[1]+","+msgText[2];
        if(msgText[0].equals("button"))
        {                
            Intent i = new Intent(context,Second.class);
            i.putExtra("msg",newstr);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
            context.startActivity(i);
        }
    }
    this.abortBroadcast();
}



}

清单文件是:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name="Second" class=".second"
        android:label="Demo">
    </activity>
    <receiver android:name=".Demo">
        <intent-filter android:priority="100">
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
</application>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>

我想知道的是当我的应用程序收到短信时如何播放声音?

我很困惑我应该在哪里实现代码,因为在分析数据之后我会切换到第二个屏幕(如果msg是特定格式的话)。

1 个答案:

答案 0 :(得分:3)

您可以在收到短信时使用NotificationManager播放声音。只需将声音文件放在res / raw。

NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();         
notification.sound = Uri.parse("android.resource://com.your.package/raw/sound_file");
nm.notify(0, notification);