我需要从我的 AsyncTask 发送短信。所以我创建了这个名为 SMS 的活动。我的 AsyncTask 我得到了这个构造函数:
public AsyncTask(Context pContext, TextView pTxtWorkProgress, TextView pTxtMsg, ProgressBar pProgressbar_line, SMS pSmsActivity){
context = pContext;
txtMsg = pTxtMsg;
txtWorkProgress = pTxtWorkProgress;
progressbar_line = pProgressbar_line;
smsActivity = pSmsActivity;
}
然后,在我的 doInBackground() 中,我得到了代码:
if(smsActivity != null)
smsActivity.sendSMS("9999", "4444");
else
hasErrorSms = true;
在我的 smsActivity 中,我得到了 sendSMS() 方法:
public void sendSMS(String phoneNumber, String message){
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()){
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show();
Util.mSMS_SENT_STATUS = Util.mSMS_SENT_RESULT_OK;
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
Util.mSMS_SENT_STATUS = Util.mSMS_SENT_RESULT_ERROR_GENERIC_FAILURE;
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
Util.mSMS_SENT_STATUS = Util.mSMS_SENT_RESULT_ERROR_NO_SERVICE;
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
Util.mSMS_SENT_STATUS = Util.mSMS_SENT_RESULT_ERROR_NULL_PDU;
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
Util.mSMS_SENT_STATUS = Util.mSMS_SENT_RESULT_ERROR_RADIO_OFF;
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
但它不起作用,当我尝试在 SMS 类中获取 Intent 时,我得到了 NullPointerException。
这就是我调用 AsyncTask 的方式:
new AsyncTask(this, txtWorkProgress, txtMsg, progressbar_line, new SMS()).execute(larr_what_have_to_upate_in_device.toString(), lCD_DEVIC);
我知道新的 SMS() 不起作用,有人可以告诉我该怎么做?谢谢。