Sunday, September 11, 2011

Android Programming - Send SMS

Android is for mobile, so it must preserve support to mobile function like calling and SMS.
In Android SMS can be done by starting SMS activity class via Intent or create yourself a SMS Sending class.
I'll create my own method to send SMS.
private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 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(), SENT, 
                                Toast.LENGTH_SHORT).show();

                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, null);        
    }
You need to argument to start this function, sms number and sms message. Just fill it and you're done. It check too for error that may found.
You can check SMS using Emulator, create 2 emulator and you can send a sms from one to another emulator using the emulator number, for example 5554 or 5556.

Categories: , , , ,

0 komentar:

Copyright © Johannes Dwi Cahyo | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com | BTheme.net      Up ↑