Skip to content Skip to sidebar Skip to footer

Display Android TOAST On Receive Of Sms

i am working on an app which shows a toast on sms is received.i want either sms content to be displayed or just an notification that sms has been received. I am using android studi

Solution 1:

Register a receiver which listens to new message. Refer these link Android - SMS Broadcast receiver and Blog : Incomming SMS Broadcast Receiver - Android Example


Solution 2:

Use the BroadcastReceiver to listen to the sms received.
Codes are here:

public class SmsReciver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    SmsMessage msg = null;
    if (null != bundle) {
        Object[] smsObj = (Object[]) bundle.get("pdus");
        for (Object object : smsObj) {
            msg = SmsMessage.createFromPdu((byte[]) object);
        Date date = new Date(msg.getTimestampMillis());//时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String receiveTime = format.format(date);
            Toast.make(context, "number:" + msg.getOriginatingAddress()
            + "   body:" + msg.getDisplayMessageBody() + "  time:"
                    + msg.getTimestampMillis(), 1000).show();
        }
    }
  }
}

Meanwhile, add this in your AndroidManifest.xml:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
...
<receiver android:name="com.dbjtech.acbxt.waiqin.SmsReciver" >
    <intent-filter android:priority="999">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Solution 3:

If your app is running on an Android version > 3.0, you'll have to include an Activity that the user can start manually after installation to bring the app out of its stopped state, a concept introduced in Android 3.1. The system will not broadcast to stopped apps, so your BroadcastReceiver won't work until the app has been explicitly launched by the user.

Apart from that, your code appears to be correct.


Post a Comment for "Display Android TOAST On Receive Of Sms"