android - BroadcastReceiver在发送短信时不调用OnReceive

时间:2017-10-19 09:24:33

标签: android broadcastreceiver

我正在创建一个应用程序,如果某个应用程序满足某个条件,它会发送一条消息,但无论何时发送该消息,接收方都不会调用onReceive方法。我尝试了回答SO问题的所有建议,但没有任何帮助我解决它。如果我的短信与这些代码一起发送,我想收到报告:

BroadcastReceiver类:

public class SendSMS extends BroadcastReceiver {

public SendSMS() {
    super();
}

@Override
public void onReceive(Context context, Intent intent) {
    int resultCode = getResultCode();
    switch (resultCode) {
        case AppCompatActivity.RESULT_OK:
            result = "Message sent.";
            break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
            result = "Error. Message not sent.";
            break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
            result = "Error: No service.";
            break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
            result = "Error: Null PDU.";
            break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
            result = "Error: Radio off.";
            break;
    }
}

}

发送文字课程:

public class SMSSender {
private Context context;
private final int MAX_SMS_MESSAGE_LENGTH = 160;
private final String SMS_SENT = "sent";
private final String SMS_DELIVERED = "delivered";


public SMSSender(Context context) {
    this.context = context;
}


public void sendSMS(String phoneNumber, String message) {
    SendSMS brSendSMS = new SendSMS();

    try {
          //##### Also tried all kinds of context ###### //
        PendingIntent piSend = PendingIntent.getBroadcast(context.getApplicationContext(), 0, new Intent(SMS_SENT), 0);

        int length = message.length();


        context.getApplicationContext().registerReceiver(brSendSMS, new IntentFilter(SMS_SENT));


        SmsManager smsManager = SmsManager.getDefault();       
        smsManager.sendTextMessage(phoneNumber, null, message, piSend, null);



    } catch (Exception ex) {
        Toast.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
    } finally {
        context.getApplicationContext().unregisterReceiver(brSendSMS);
    }
}

}

为了测试这个,我把它放在按钮点击的方法中。

        SMSSender smsSender = new SMSSender(this);
        smsSender.sendSMS("000000", "TESTING ONLY");

我在这里做错了什么?我还了解到它使用我的默认短信应用程序,说明"未发送。点击再试一次"。

0 个答案:

没有答案