Reputation: 109
I want to use intent-filter, but I cann't find android.provider.Telephony.SMS_RECEIVED
in android 4.2 or greater.
I mean I can not get code hints in the adt when i choose compile with android 4.2. But when i compile with 4.1 ,that's ok. I can get the code hints,and when the sms is coming ,i will know.
What should I do to monitor an SMS in android 4.2? Is there any way I can be notified when I receive a message?
<receiver android:name="com.itheima.mobilesafe.receiver.SmsReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
}
}
Upvotes: 1
Views: 123
Reputation: 327
Note: As of Android M you need to get the runtime permissions and the below code won't run as it is until runtime permission is requested
public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
SmsMessage smsMessage;
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
if (null != sms) {
for (int i = 0; i < sms.length; ++i) {
if (Build.VERSION.SDK_INT >= 23) {
smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], intent.getStringExtra("format"));
} else {
smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
}
if (null != smsMessage) {
String smsBody = smsMessage.getMessageBody();
String address = smsMessage.getOriginatingAddress();
//your logic here
} else {
//handle null case;
}
}
}
}
}
}
}
And in your Manifest
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<receiver
android:name=".SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Upvotes: 3