public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
@Override
public void onReceive(Context context, Intent intent) {
final Bundle data = intent.getExtras();
final Object[] pdus = (Object[]) data.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
String sender = smsMessage.getDisplayOriginatingAddress();
//You must check here if the sender is your provider and not another one with same text.
Log.i("Sender id ",sender);
String messageBody = smsMessage.getMessageBody();
Log.i("get Message body ",messageBody);
messageBody=smsMessage.getDisplayMessageBody();
Log.i("Message Body ",messageBody);
//Pass on the text to our listener.
mListener.messageReceived(messageBody);
}
}
public static void bindListener(SmsListener listener) {
mListener = listener;
}
}
public interface SmsListener {
public void messageReceived(String messageText);
}
in the fragement/dialog calling :
SmsReceiver.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(getContext(),"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
@Override
public void onResume() {
Log.i("In resume ","resume");
SmsReceiver.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(getContext(),"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
super.onResume();
}
@Override
public void onPause() {
Log.i("In pause ","pause");
super.onPause();
SmsReceiver.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
Log.d("Text",messageText);
Toast.makeText(getContext(),"Message: "+messageText,Toast.LENGTH_LONG).show();
}
});
}
<receiver android:name="services.SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
I am not getting any error and nothing is prints in log also. Don't know what wrong going on. Even no print from the broadcast receiver. I think code in onResume is also not executing.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…