短信接收器没有工作

时间:2014-09-17 19:42:03

标签: java android eclipse sms telephony

我是Android短信的新手,我正在尝试研究它。所以我正在尝试制作一个总是在后台运行的Android应用程序,当我收到带有" hello"(有人通过短信发送"你好"到我的手机)内容的短信时音乐会播放。

我在互联网上搜索过,我建立了一个可以在AVD上工作的项目,但是当我在手机上测试它时,它没有工作:

import info.kfsoft.android.R.raw;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.TextView;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver
{

    MediaPlayer ourSong;
    //static final int uniqueID=12345;
    TextView display;

    public void onReceive(Context context, Intent intent)
    {
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        ourSong = MediaPlayer.create(context, R.raw.music2);


        Bundle myBundle = intent.getExtras();
        SmsMessage [] messages = null;
        String strMessage = "";

        if (myBundle != null)
        {
            Object [] pdus = (Object[]) myBundle.get("pdus");
            messages = new SmsMessage[pdus.length];

            for (int i = 0; i < messages.length; i++)
            {
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
          //      strMessage += "SMS From the king him self: " + messages[i].getOriginatingAddress();
      //          strMessage += " : ";
               strMessage += messages[i].getMessageBody();
         //       strMessage += "\n";


            }
    //max volume
            AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                am.setStreamVolume(AudioManager.STREAM_MUSIC,am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),0);

            Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();

     //       Notification n=new    Notification(android.R.drawable.)
     //       nm.notify(uniqueID,n);

            ourSong.start();
        }
    }
    public void a(){

    }

}

THX。

1 个答案:

答案 0 :(得分:2)

也许您的意图优先级太低,系统安装的SMSApp会在您的应用程序之前收到消息。尝试添加优先级=&#34; 999&#34;

<receiver android:name="OnAlarmReceiver">
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter>
</receiver>

另一个技巧是不在AndroidManifest.xml文件中注册SMS_RECEIVED,而是在应用程序代码中以编程方式注册。以下是我实际将多个事件注册到同一个广播接收器的示例。

broadcastReceiver = new EventReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY-1);
registerReceiver(broadcastReceiver, filter);