您好,我创建了一个自动短信应用程序,该应用程序会在收到Firebase通知时自动发送短信。我可以发送扩展FirebaseMessagingService
的SMS。现在,要获取发送状态,我在主要活动中创建了一个广播接收器。
在这里,我仅在打开App时才能获得SMS发送状态。即使应用程序是背景,我也需要得到它。
我的收信人是:
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = null;
switch (getResultCode()) {
case Activity.RESULT_OK:
message = "Message sent!";
Log.e("DATA", message);
unregisterReceiver(receiver);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
message = "Error. Message not sent.";
Log.e("DATA", message);
unregisterReceiver(receiver);
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
message = "Error: No service.";
Log.e("DATA", message);
unregisterReceiver(receiver);
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
message = "Error: Null PDU.";
Log.e("DATA", message);
unregisterReceiver(receiver);
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
message = "Error: Radio off.";
Log.e("DATA", message);
unregisterReceiver(receiver);
break;
}
}
};
在onCreate中注册接收者:
registerReceiver(receiver, new IntentFilter(Constants.SMS_SENT));
我的Firebase服务使用以下方式发送短信:
private void sendSms(String phonenumber[],String message)
{
SmsManager manager = SmsManager.getDefault();
PendingIntent piSend = PendingIntent.getBroadcast(this, 0, new Intent(Constants.SMS_SENT), 0);
PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0, new Intent(Constants.SMS_DELIVERED), 0);
int length = message.length();
if(length > MAX_SMS_MESSAGE_LENGTH)
{
ArrayList<String> messagelist = manager.divideMessage(message);
for(String number : phonenumber) {
manager.sendMultipartTextMessage(number, null, messagelist, null, null);
}
}
else
{
for(String number : phonenumber) {
manager.sendTextMessage(number, null, message, piSend, piDelivered);
}
}
}
答案 0 :(得分:1)
您是否在清单类中注册? 如果没有,则在清单中注册您的广播,并使用单独的类进行广播 您可以从这里阅读更多内容。 https://www.c-sharpcorner.com/UploadFile/8836be/how-to-create-global-broadcast-receiver-and-test-service-in/
答案 1 :(得分:0)
如果要在onPause()中注销接收器,则它可能无法工作。尝试将注销代码移动到onStop()或onDestroy()