Pages

Friday 24 August 2012

Send sms in android

    Hope this will help you...:)

public void sendMessage(String text, String address) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        SmsManager smsManager = SmsManager.getDefault();
        ArrayList<String> textParts = smsManager.divideMessage("message you want to send");
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Message sent successfully.", Toast.LENGTH_SHORT).show();
                        Log.i(TAG,"SMS sent");
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
                        Log.i(TAG,"Generic failure");
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
                        Log.i(TAG,"No service");
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
                        Log.i(TAG,"Null PDU");
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
                        Log.i(TAG,"Radio off");
                        break;
                }
            }
        }, new IntentFilter(SENT));
        ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
        for (int i = 0; i < textParts.size(); i += 1)
            sentIntents.add(PendingIntent.getBroadcast(this, i, new Intent(SENT), 0));
        if (address.length() != 0) {
            Log.i(TAG,"address=" + address);
            Log.i(TAG,"textParts=" + textParts.toString());
            try {
                smsManager.sendMultipartTextMessage(address,null,textParts,sentIntents,null);
            } catch (IllegalArgumentException e) {
                Toast.makeText(getBaseContext(), "Number invalid: " + address, Toast.LENGTH_LONG).show();
                Log.e(TAG,e.toString());
            } catch (NullPointerException e) {
                Log.e(TAG,e.toString());
            }
        }
    }