我目前有一个我想要使用的方法是OnReceive
public class IncomingSMSReceiver extends BroadcastReceiver {
private String senderNumber;
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String message = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
message = msgs[i].getMessageBody();
senderNumber = msgs[i].getOriginatingAddress();
}
senderNumber = msgs[0].getOriginatingAddress();
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
sendMessage(senderNumber, "Thank you for sending me a message");
}
}
我想在这个类中使用这个方法,但我不确定在调用方法时要放在方括号中。
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
IncomingSMSReceiver receiver = new IncomingSMSReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
receiver.onReceive();
有人可以帮我告诉我在onReceive()括号中输入什么内容吗?
修改
我做了你说的并改变了我的代码,我也没有在ActivityMaps中调用onReceive。所以这是我的代码,它仍然不会回复&#34;测试&#34;短信,当&#34;更新&#34;短信发送给我。
public class IncomingSMSReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus.length == 0) {
return;
}
SmsMessage[] messages = new SmsMessage[pdus.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
sb.append(messages[i].getMessageBody());
}
String sender = messages[0].getOriginatingAddress();
String message = sb.toString();
String txtSMS="Testing";
if (message.startsWith("UPDATE"))
{
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
this.abortBroadcast();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(sender, null, txtSMS, null, null);
}
}
}
}
我的清单文件
receiver android:name=".IncomingSMSReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.PHONE_STATE" />
<action android:name="PACKAGE_NAME.android.action.broadcast"/>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
答案 0 :(得分:0)
尝试更新您的清单文件:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<!-- inside your application tag -->
<receiver android:name=".IncomingSMSReceiver">
<intent-filter android:priority="2147483647" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>