How to read the incoming message using service in background in android?

前端 未结 1 357
甜味超标
甜味超标 2020-12-24 09:10

I am developing an android application in that i want to read the incoming message without knowing the user.I want to always run the incoming message checker in background.I

1条回答
  •  遥遥无期
    2020-12-24 09:41

    Take a look at BroadCastReceivers you must implement and register a Reciever for android.provider.Telephony.SMS_RECEIVED

    Here is a code snippet that lets you read messages as they arrive.

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.telephony.SmsMessage;
    import android.widget.Toast;
    
    public class SMSReceiver extends BroadcastReceiver
    {
        public void onReceive(Context context, Intent intent)
        {
            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: " + messages[i].getOriginatingAddress();
                    strMessage += " : ";
                    strMessage += messages[i].getMessageBody();
                    strMessage += "\n";
                }
    
                Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    And here what you have to add to your AndroidManifest.xml file:

    
    
    
         
             
         
    
    

    0 讨论(0)
提交回复
热议问题