如何使用Android在BACKGROUND中发送短信息?

前端之家收集整理的这篇文章主要介绍了如何使用Android在BACKGROUND中发送短信息?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我来自 iphone开发,您不能在后台发送短信,而不要求用户确认发送.可以在 android的背景中发送短信,以便不需要用户干预?

解决方法

发送短信和SMS-Delivery通知作为吐司.

方法调用如下.

sendSMS("98********","This is test message");

方法签名如下.

/*
 * BroadcastReceiver mBrSend; BroadcastReceiver mBrReceive;
 */
private void sendSMS(String phoneNumber,String message) {
    ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
    ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
    PendingIntent sentPI = PendingIntent.getBroadcast(mContext,new Intent(mContext,SmsSentReceiver.class),0);
    PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext,SmsDeliveredReceiver.class),0);
    try {
        SmsManager sms = SmsManager.getDefault();
        ArrayList<String> mSMSMessage = sms.divideMessage(message);
        for (int i = 0; i < mSMSMessage.size(); i++) {
            sentPendingIntents.add(i,sentPI);
            deliveredPendingIntents.add(i,deliveredPI);
        }
        sms.sendMultipartTextMessage(phoneNumber,null,mSMSMessage,sentPendingIntents,deliveredPendingIntents);

    } catch (Exception e) {

        e.printStackTrace();
        Toast.makeText(getBaseContext(),"SMS sending Failed...",Toast.LENGTH_SHORT).show();
    }

}

现在还有两个类SmsDeliveredReceiver,SmsSentReceiver如下.

public class SmsDeliveredReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context,Intent arg1) {
    switch (getResultCode()) {
    case Activity.RESULT_OK:
        Toast.makeText(context,"SMS delivered",Toast.LENGTH_SHORT).show();
        break;
    case Activity.RESULT_CANCELED:
        Toast.makeText(context,"SMS not delivered",Toast.LENGTH_SHORT).show();
        break;
    }
}

}

现在SMSSentReceiver.

public class SmsSentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context,"SMS Sent",Toast.LENGTH_SHORT).show();

        break;
    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
        Toast.makeText(context,"SMS generic failure",Toast.LENGTH_SHORT)
                .show();

        break;
    case SmsManager.RESULT_ERROR_NO_SERVICE:
        Toast.makeText(context,"SMS no service",Toast.LENGTH_SHORT)
                .show();

        break;
    case SmsManager.RESULT_ERROR_NULL_PDU:
        Toast.makeText(context,"SMS null PDU",Toast.LENGTH_SHORT).show();
        break;
    case SmsManager.RESULT_ERROR_RAdio_OFF:
        Toast.makeText(context,"SMS radio off",Toast.LENGTH_SHORT).show();
        break;
    }
}

}

现在Permissions打开你的AndroidManifest.xml并添加下面的行

<uses-permission android:name="android.permission.SEND_SMS"/>

并完成…….

原文链接:https://www.f2er.com/android/313396.html

猜你在找的Android相关文章