Вопрос

I am trying to figure out how do I read incoming SMS messages in Android and perform a specific task, say ring an alarm, when a SMS with the text 'RingAlarm' comes in.

I figure out using the BroadcastReciever class to read the SMS, but how do I perform specific action when a message with a pre-defined text arrives. Can anyone guide me which class and/or method do I need to use for that and how?

public class IncomingSms extends BroadcastReceiver {

String key = MainActivity.keyword; //Keyword is a variable in MainActivity.
                       //I guess, my mistake is in accessing this variable in the IncomingSms class.

 @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String sms = 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";   
                sms = msgs[i].getMessageBody().toString();

            }

            //---display the new SMS message---
            //Toast.makeText(context, str, Toast.LENGTH_SHORT).show();


            //---compare received message with keyword
            if(sms==key)
                {
                  Toast toast = Toast.makeText(context, "Keyword Recieved", Toast.LENGTH_LONG);
                  toast.show();
                }


        }                         
    }

Thanks in advance!

Это было полезно?

Решение

This is my simple module to solve your problem.

Let's assume that keyword is "RING".

  1. MyReceiver : is a class file which is used to detect the keyword "RING" and going to start RingActivity.

  2. RingActivity : is going to ring your device no matter if it is in Silent Mode or Vibrate Mode.

MyReceiver

public class MyReceiver extends BroadcastReceiver
{
    final SmsManager sms = SmsManager.getDefault();
    @Override
    public void onReceive(Context context, Intent intent) 
    {       
        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
        {       
            // Retrieves a map of extended data from the intent.
            final Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String str = "";

            try
            { 
                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";
                    }
                    String replyPhone = msgs[0].getOriginatingAddress();
                    String request = msgs[0].getMessageBody().toString();

                    if(request.equals("RING"))                      
                    {
                        this.abortBroadcast();
                        Intent i = new Intent(context, RingActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.putExtra("num", replyPhone);
                        i.putExtra("msg", request);
                        context.startActivity(i);
                    }
                }
            }
            catch (Exception e) 
            {
                Log.e("MyReceiver", "Exception smsReceiver" +e);

            }
        }//close if
    }//close onReceive();
}

RingActivity

public class RingActivity extends Activity {

final Context context = this;
MediaPlayer mp = new MediaPlayer();

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Bundle extras = getIntent().getExtras(); 
    String num = extras.getString("num");
    String msg = extras.getString("msg");

    int duration = Toast.LENGTH_LONG;
    Toast toast = Toast.makeText(context, "I AM At Reciver\nsenderNum: "+num+", message: " + msg, duration);
    toast.show();

    SmsManager smsManager = SmsManager.getDefault();
    if(IsRingerSilent() || IsVibrate())
    {
        smsManager.sendTextMessage(num, null, "Device turned to ringing mode.. && It's Ringing..", null, null);
        AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
        audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        mp.setLooping(true);
        try 
        {
            AssetFileDescriptor afd;
            afd = getAssets().openFd("fire_siren.mp3");
            mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            mp.prepare();
            mp.start();
        }
        catch (IllegalStateException e)
        {
            e.printStackTrace();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    else
    {
        smsManager.sendTextMessage(num, null, "Device Ringing...", null, null);
        AudioManager audioManager= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
        audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); 
        mp.setLooping(true);
        try 
        {
            AssetFileDescriptor afd;
            afd = getAssets().openFd("fire_siren.mp3");
            mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            mp.prepare();
            mp.start();
        }
        catch (IllegalStateException e)
        {
            e.printStackTrace();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }



    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

    // Setting Dialog Title
    alertDialogBuilder.setTitle("Device Ringing");

    // Setting Dialog Message
    alertDialogBuilder.setMessage("Sender : "+num+"\n"+"Message : "+msg);




    alertDialogBuilder.setNegativeButton("Dialog Close", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) 
        {
            if(mp.isPlaying())
            {
                mp.setLooping(false);
                mp.stop();
            }
        dialog.cancel();
        finish();
       }
    }); 

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    //show dialog
    alertDialog.show();


}

private boolean IsVibrate() 
{
 AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

     if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE )
     {
         return true;
     }
     else
     {
         return false;
     }      
}

private boolean IsRingerSilent() 
{
    AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

     if(audioManager.getRingerMode()==AudioManager.RINGER_MODE_SILENT )
     {
         return true;
     }
     else
     {
         return false;
     }
}

public boolean onKeyDown(int keycode, KeyEvent ke)
{
    if(keycode==KeyEvent.KEYCODE_BACK)
    {

        if(mp.isPlaying())
        {
            mp.setLooping(false);
            mp.stop();
        }
        finish();           
    }
    return true;
}


}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top