gpt4 book ai didi

android - 获取发送的短信

转载 作者:行者123 更新时间:2023-11-30 03:12:58 25 4
gpt4 key购买 nike

我正在制作一个在 Android 上发送 SMS 消息的程序。发送工作正常,但我不知道发送了哪条消息。

下面的代码是代码的主要部分:它从字符串 resp 中读取许多消息,随机等待一段时间并发送每条消息。但是,我不知道 onReceive 方法确认的是哪条短信。

所以,这是我的问题:我如何知道 onReceive 发送的哪条 SMS 正在确认?

我试图寻找contextintent 这两个参数的变量和方法,但没有帮助。

 final PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"),0);
registerReceiver(new BroadcastReceiver() {

// executed when the sms is sended
public void onReceive(Context context, Intent intent) {
switch(getResultCode()){
case Activity.RESULT_OK:
Toast.makeText(getApplicationContext(), "SMS sended",
Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_LONG).show();
break;
}
}
}, new IntentFilter("SMS_SENT"));

// resp is a String with a number and a body by line: <number><body>\n<number><body>\n...
final Scanner scan = new Scanner(resp);
String to;
String body;
SmsManager sms = SmsManager.getDefault();

while (scan.hasNext()){
long r = new Random().nextInt(20000) + 1000;
synchronized(this){
try {
this.wait(r);
} catch (InterruptedException e) {
Toast.makeText(getApplicationContext(), "ERROR on WAIT",Toast.LENGTH_LONG).show();
}
}
to = scan.next();
body = scan.nextLine();
Toast.makeText(getApplicationContext(), "Sending to " + to,
Toast.LENGTH_LONG).show();

sms.sendTextMessage(to, null, body, pi, null);
}
scan.close();

最佳答案

编辑:稍微修改代码以便能够保存 BroadcastReceiver 以用于注销

您可以通过向传递给 PendingIntent.getBroadcast()Intent 添加“extras”或通过在“ACTION”中编码消息 ID 来实现此目的您放入传递给 getBroadcast()Intent

由于在 PendingIntent 中处理 extras 的方式,使用“extras”更加复杂。这是我在 ACTION 中对消息 ID 进行编码的意思的示例:

long messageID = ...; // This is the message ID (some unique value so that you know which message was sent)
String actionString = "SMS_SENT_" + messageID;

final PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(actionString),0);
BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {

// executed when the sms is sended
public void onReceive(Context context, Intent intent) {
// Extract message ID from action
String action = intent.getAction();
long id = -1; // Message ID
if (action != null) {
id = Long.parseLong(action.substring(9));
// id is now your message ID
}
switch(getResultCode()){
case Activity.RESULT_OK:
Toast.makeText(getApplicationContext(), "SMS sended",
Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_LONG).show();
break;
}
}
};
registerReceiver(myBroadcastReceiver, new IntentFilter(actionString));
// Here you can save myBroadcastReceiver somewhere (in an ArrayList maybe?)
// so that you can unregister later

关于android - 获取发送的短信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20616731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com