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);
}
不工作在fragement /對話框呼叫:自動短信閱讀Android的
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" />
我沒有得到任何錯誤,沒有什麼是日誌打印也。不知道發生了什麼問題。即使沒有從廣播接收器打印。我認爲onResume中的代碼也沒有執行。
有您註冊短信-R 'AndroidMenifest'上的接收者? –
你在測試這個設備是小米嗎? –
是的。 @android_griezmann –