SMSReceiver.java
public class SMSReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String str = "";
if (bundle != null) {
Object [] pdus = (Object[])bundle.get("pdus");
SmsMessage [] msgs = new SmsMessage[pdus.length];
String [] lmsg = new String[2048];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage
.createFromPdu((byte[]) pdus[i]);
str += msgs[i].getOriginatingAddress()
+ "\n " +
msgs[i].getMessageBody().toString()
+"\n";
}
for (int j = 0; j < lmsg.length ; j++) {
lmsg[j] = str;
} Toast.makeText(context, str, Toast.LENGTH_LONG).show();
}
}
}
2.RedirectActivity
public class RedirectActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
intent.setClass(RedirectActivity.this, ParentActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
我想从SMS获取数据到ParentActivity。
我在SMSReceiver和RedirectActivity之间遇到了问题。它没有用。
答案 0 :(得分:0)
请尝试这个兄弟
public class IncomingSms extends BroadcastReceiver {
private static SmsListener mListener;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data = intent.getExtras();
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.
String messageBody = smsMessage.getMessageBody();
//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);
}
活动获取消息
IncomingSms.bindListener(new SmsListener() {
@Override
public void messageReceived(String messageText) {
Log.d("Text", messageText);
Toast.makeText(VerifyOTPActivity.this, "Message: " + messageText, Toast.LENGTH_LONG).show();
}
});
不要忘记此清单文件
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<receiver android:name=".IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>