EzDevInfo.com

sms interview questions

Top sms frequently asked interview questions

Intercepting Outgoing SMS

Is it possible to intercept outgoing SMS before it is actually sent, get its contents then ignore / send it according to some criteria?

eg. block all international text (numbers with leading 00), but allow everything else.


Source: (StackOverflow)

SMS from web application

I just want to send SMS from my web application in PHP. Can anyone tell me how to do this? What all things I need to do for this?


Source: (StackOverflow)

Advertisements

Broadcast Receiver within a Service

I am trying to start up a BroadcastReceiver within a Service. What I am trying to do is have a background running service going that collects incoming text messages, and logs incoming phone calls. I figured the best way to go about this is to have a service running that incorporates a broadcast receiver that can catalog either.

How do i go about doing this? I already have my service up and running.


Source: (StackOverflow)

Android - SMS Broadcast receiver

I have been trying to get this program to work but so far having no luck. I cannot find where I am doing wrong. I'm not sure if there's something wrong with the code, or debugging.

I'm trying to be notified if a new SMS arrives.

Here is my program:

package Technicaljar.SMSBroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSBroadcastReceiver extends BroadcastReceiver {

        private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
        private static final String TAG = "SMSBroadcastReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
             Log.i(TAG, "Intent recieved: " + intent.getAction());

                if (intent.getAction() == SMS_RECEIVED) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        Object[] pdus = (Object[])bundle.get("pdus");
                        final SmsMessage[] messages = new SmsMessage[pdus.length];
                        for (int i = 0; i < pdus.length; i++) {
                            messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        }
                        if (messages.length > -1) {
                            Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
                        }
                    }
                }
           }
    }

And the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="Technicaljar.SMSBroadcastReceiver"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true" >
        <receiver android:name=".SMSBroadcastReceiver">
            <intent-filter>
                <action android:name="android.provider.telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest> 

I am sending SMS through Telnet, and I cannot see any Intent received messages in the logcat. Here is my logcat from the time of installation.

D/AndroidRuntime(  478): 
D/AndroidRuntime(  478): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime(  478): CheckJNI is ON
D/AndroidRuntime(  478): --- registering native functions ---
D/AndroidRuntime(  478): Shutting down VM
D/dalvikvm(  478): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(  478): NOTE: attach of thread 'Binder Thread #3' failed
D/Mms:app (  220): getSmsNewMessageNotificationInfo: count=14, first addr=12345, thread_id=4
D/dalvikvm(  151): GC_EXPLICIT freed 391 objects / 22552 bytes in 65ms
D/dalvikvm(  220): GC_EXPLICIT freed 926 objects / 44840 bytes in 73ms

So the SMS seems to be received by the emulator, but looks like the no intents are firing. What am I doing wrong here? After installing, do I have to somehow 'start' this receiver? Because when I install, I get

 [2010-11-07 21:24:41 - SMSBroadcastReceiver] No Launcher activity found!
[2010-11-07 21:24:41 - SMSBroadcastReceiver] The launch will only sync the application package on the device!

So I'm wondering if something's wrong here.


Source: (StackOverflow)

Cheapest way to send SMS for number verification? [closed]

My application needs to verify phone numbers that are provided by the user. What is the absolute cheapest way to send an SMS to a phone? Which company/API should I go to? I'm not looking for a hack solution to send out 10 SMS a month kind of thing, I need to roll this out for a company that will be sending mass amount of verifications. But they want to do it at the lowest cost. (Each user will only need to verify once)

Sorry forgot mention the SMS needs to be international


Source: (StackOverflow)

Read inbox messages of a particular number and display them in an activity

I am trying to read messages from an inbox and display them in an activity. My activity contains a button and listview. When I click on the button, all messages from the inbox are displayed. But my requirement is that I need to view messages from a particular number. My application is not running when I get messages from that number when I click on the click button only specific messages (associated with a particular number) must be updated. Here's the relevant code.

myActivity.java:

public class SecureMessagesActivity extends Activity implements OnClickListener, OnItemClickListener {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme( android.R.style.Theme_Light );
        setContentView(R.layout.main);
        this.findViewById( R.id.UpdateList ).setOnClickListener( this );
    }

    ArrayList<String> smsList = new ArrayList<String>();

    public void onItemClick( AdapterView<?> parent, View view, int pos, long id ) {
        try {
            String[] splitted = smsList.get( pos ).split("\n"); 
            String sender = splitted[0];
            String encryptedData = "";

            for ( int i = 1; i < splitted.length; ++i ) {
                encryptedData += splitted[i];
            }
            String data = sender + "\n" + StringCryptor.decrypt( new String(SmsReceiver.PASSWORD), encryptedData );
            Toast.makeText( this, data, Toast.LENGTH_SHORT ).show();
        } 
        catch (Exception e) {
                e.printStackTrace();
        }
    }

    public void onClick( View v ) {
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query( Uri.parse( "content://sms/inbox" ), null, null, null, null);

        int indexBody = cursor.getColumnIndex( SmsReceiver.BODY );
        int indexAddr = cursor.getColumnIndex( SmsReceiver.ADDRESS );

        if ( indexBody < 0 || !cursor.moveToFirst() ) return;

        smsList.clear();

        do {
            String str = "Sender: " + cursor.getString( indexAddr ) + "\n" + cursor.getString( indexBody );
            smsList.add( str );
        }
        while( cursor.moveToNext() );

        ListView smsListView = (ListView) findViewById( R.id.SMSList );
        smsListView.setAdapter( new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, smsList) );
        smsListView.setOnItemClickListener( this );
    }
} 

SmsReceiver.java:

public class SmsReceiver extends BroadcastReceiver {
    public static final String SMS_EXTRA_NAME = "pdus";
    public static final String SMS_URI = "content://sms";

    public static final String ADDRESS = "address";
    public static final String PERSON = "person";
    public static final String DATE = "date";
    public static final String READ = "read";
    public static final String STATUS = "status";
    public static final String TYPE = "type";
    public static final String BODY = "body";
    public static final String SEEN = "seen";

    public static final int MESSAGE_TYPE_INBOX = 1;
    public static final int MESSAGE_TYPE_SENT = 2;

    public static final int MESSAGE_IS_NOT_READ = 0;
    public static final int MESSAGE_IS_READ = 1;

    public static final int MESSAGE_IS_NOT_SEEN = 0;
    public static final int MESSAGE_IS_SEEN = 1;


    public static final byte[] PASSWORD = new byte[]{ 0x20, 0x32, 0x34, 0x47, (byte) 0x84, 0x33, 0x58 };

    public void onReceive( Context context, Intent intent ) {

        Bundle extras = intent.getExtras();
        String messages = "";

        if ( extras != null ) {
            Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
            ContentResolver contentResolver = context.getContentResolver();

            for ( int i = 0; i < smsExtra.length; ++i ) {
                SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);

                String body = sms.getMessageBody().toString();
                String address = sms.getOriginatingAddress();

                messages += "SMS from " + address + " :\n";                    
                messages += body + "\n";
                putSmsToDatabase( contentResolver, sms );
            }

            // Display SMS message
            Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
        }

        // WARNING!!! 
        // If you uncomment next line then received SMS will not be put to incoming.
        // Be careful!
        // this.abortBroadcast(); 
    }

    private void putSmsToDatabase( ContentResolver contentResolver, SmsMessage sms ) {
        ContentValues values = new ContentValues();
        values.put( ADDRESS, sms.getOriginatingAddress() );
        values.put( DATE, sms.getTimestampMillis() );
        values.put( READ, MESSAGE_IS_NOT_READ );
        values.put( STATUS, sms.getStatus() );
        values.put( TYPE, MESSAGE_TYPE_INBOX );
        values.put( SEEN, MESSAGE_IS_NOT_SEEN );
        try {
            String encryptedPassword = StringCryptor.encrypt( new String(PASSWORD), sms.getMessageBody().toString() ); 
            values.put( BODY, encryptedPassword );
        }
        catch ( Exception e ) { 
            e.printStackTrace(); 
        }

        // Push row into the SMS table
        contentResolver.insert( Uri.parse( SMS_URI ), values );
    }
}

Source: (StackOverflow)

How to send and receive SMS from android app? [closed]

I want to add sms sending feature in my app and also want option in which user can select the contacts from the contact list directly from the application. Is there way that contact list can be integrated with my application.

Thanks


Source: (StackOverflow)

How to programmatically send SMS on the iPhone?

Does anybody know if it's possible, and how, to programmatically send a SMS from the iPhone, with the official SDK / Cocoa Touch?


Source: (StackOverflow)

How can I read SMS messages from the inbox programmatically in Android?

I want to retrieve the SMS messages from the inbox and display them?


Source: (StackOverflow)

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I have figured out how to send and receive SMS messages. To send SMS messages I had to call the sendTextMessage() and sendMultipartTextMessage() methods of the SmsManager class. To receive SMS messages, I had to register a receiver in the AndroidMainfest.xml file. Then I had to override the onReceive() method of the BroadcastReceiver. I have included examples below.

MainActivity.java

public class MainActivity extends Activity {
    private static String SENT = "SMS_SENT";
    private static String DELIVERED = "SMS_DELIVERED";
    private static int MAX_SMS_MESSAGE_LENGTH = 160;

    // ---sends an SMS message to another device---
    public static void sendSMS(String phoneNumber, String message) {

        PendingIntent piSent = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
        PendingIntent piDelivered = PendingIntent.getBroadcast(mContext, 0,new Intent(DELIVERED), 0);
        SmsManager smsManager = SmsManager.getDefault();

        int length = message.length();          
        if(length > MAX_SMS_MESSAGE_LENGTH) {
            ArrayList<String> messagelist = smsManager.divideMessage(message);          
            smsManager.sendMultipartTextMessage(phoneNumber, null, messagelist, null, null);
        }
        else
            smsManager.sendTextMessage(phoneNumber, null, message, piSent, piDelivered);
        }
    }

    //More methods of MainActivity ...
}

SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver {
    private final String DEBUG_TAG = getClass().getSimpleName().toString();
    private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private Context mContext;
    private Intent mIntent;

    // Retrieve SMS
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mIntent = intent;

        String action = intent.getAction();

        if(action.equals(ACTION_SMS_RECEIVED)){

            String address, str = "";
            int contactId = -1;

            SmsMessage[] msgs = getMessagesFromIntent(mIntent);
            if (msgs != null) {
                for (int i = 0; i < msgs.length; i++) {
                    address = msgs[i].getOriginatingAddress();
                    contactId = ContactsUtils.getContactId(mContext, address, "address");
                    str += msgs[i].getMessageBody().toString();
                    str += "\n";
                }
            }   

            if(contactId != -1){
                showNotification(contactId, str);
            }

            // ---send a broadcast intent to update the SMS received in the
            // activity---
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction("SMS_RECEIVED_ACTION");
            broadcastIntent.putExtra("sms", str);
            context.sendBroadcast(broadcastIntent);
        }

    }

    public static SmsMessage[] getMessagesFromIntent(Intent intent) {
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        byte[][] pduObjs = new byte[messages.length][];

        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[]) messages[i];
        }
        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];
        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }
        return msgs;
    }

    /**
    * The notification is the icon and associated expanded entry in the status
    * bar.
    */
    protected void showNotification(int contactId, String message) {
        //Display notification...
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_MMS" />
    <uses-permission android:name="android.permission.WRITE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher_icon"
        android:label="@string/app_name" >

        <activity
            //Main activity...
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            //Activity 2 ...
        </activity>
        //More acitivies ...

        // SMS Receiver
        <receiver android:name="com.myexample.receivers.SMSReceiver" >
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

However, I was wondering if you could send and receive MMS messages in a similar fashion. After doing some research, many examples provided on blogs simply pass an Intent to the native Messaging application. I am trying to send an MMS without leaving my application. There doesn't seem to be a standard way of sending and receiving MMS. Has anyone gotten this to work?

Also, I am aware that the SMS/MMS ContentProvider is not a part of the official Android SDK, but I was thinking someone may have been able to implement this. Any help is greatly appreciated.

Update

I have added a BroadcastReceiver to the AndroidManifest.xml file to receive MMS messages

<receiver android:name="com.sendit.receivers.MMSReceiver" >
    <intent-filter>
        <action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />

        <data android:mimeType="application/vnd.wap.mms-message" />
    </intent-filter>
</receiver>

In the MMSReceiver class, the onReceive() method is only able to grab the phoneNumber that the message was sent from. How do you grab other important things from an MMS such as the file path to the media attachment (image/audio/video), or the text in the MMS?

MMSReceiver.java

public class MMSReceiver extends BroadcastReceiver {
    private final String DEBUG_TAG = getClass().getSimpleName().toString();
    private static final String ACTION_MMS_RECEIVED = "android.provider.Telephony.WAP_PUSH_RECEIVED";
    private static final String MMS_DATA_TYPE = "application/vnd.wap.mms-message";

     // Retrieve MMS
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        String type = intent.getType();

        if(action.equals(ACTION_MMS_RECEIVED) && type.equals(MMS_DATA_TYPE)){

            Bundle bundle = intent.getExtras();

            Log.d(DEBUG_TAG, "bundle " + bundle);
            SmsMessage[] msgs = null;
            String str = "";
            int contactId = -1;
            String address;

            if (bundle != null) {

                byte[] buffer = bundle.getByteArray("data");
                Log.d(DEBUG_TAG, "buffer " + buffer);
                String incomingNumber = new String(buffer);
                int indx = incomingNumber.indexOf("/TYPE");
                if(indx>0 && (indx-15)>0){
                    int newIndx = indx - 15;
                    incomingNumber = incomingNumber.substring(newIndx, indx);
                    indx = incomingNumber.indexOf("+");
                    if(indx>0){
                        incomingNumber = incomingNumber.substring(indx);
                        Log.d(DEBUG_TAG, "Mobile Number: " + incomingNumber);
                    }
                }

                int transactionId = bundle.getInt("transactionId");
                Log.d(DEBUG_TAG, "transactionId " + transactionId);

                int pduType = bundle.getInt("pduType");
                Log.d(DEBUG_TAG, "pduType " + pduType);

                byte[] buffer2 = bundle.getByteArray("header");      
                String header = new String(buffer2);
                Log.d(DEBUG_TAG, "header " + header);

                if(contactId != -1){
                    showNotification(contactId, str);
                }

                // ---send a broadcast intent to update the MMS received in the
                // activity---
                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction("MMS_RECEIVED_ACTION");
                broadcastIntent.putExtra("mms", str);
                context.sendBroadcast(broadcastIntent);

            }
        }

    }

    /**
    * The notification is the icon and associated expanded entry in the status
    * bar.
    */
    protected void showNotification(int contactId, String message) {
        //Display notification...
    }
}

According to the Documentation of android.provider.Telephony:

Broadcast Action: A new text based SMS message has been received by the device. The intent will have the following extra values:

pdus - An Object[] of byte[]s containing the PDUs that make up the message.

The extra values can be extracted using getMessagesFromIntent(android.content.Intent) If a BroadcastReceiver encounters an error while processing this intent it should set the result code appropriately.

 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
 public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

Broadcast Action: A new data based SMS message has been received by the device. The intent will have the following extra values:

pdus - An Object[] of byte[]s containing the PDUs that make up the message.

The extra values can be extracted using getMessagesFromIntent(android.content.Intent). If a BroadcastReceiver encounters an error while processing this intent it should set the result code appropriately.

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String DATA_SMS_RECEIVED_ACTION = "android.intent.action.DATA_SMS_RECEIVED";

Broadcast Action: A new WAP PUSH message has been received by the device. The intent will have the following extra values:

transactionId (Integer) - The WAP transaction ID

pduType (Integer) - The WAP PDU type`

header (byte[]) - The header of the message

data (byte[]) - The data payload of the message

contentTypeParameters (HashMap<String,String>) - Any parameters associated with the content type (decoded from the WSP Content-Type header)

If a BroadcastReceiver encounters an error while processing this intent it should set the result code appropriately. The contentTypeParameters extra value is map of content parameters keyed by their names. If any unassigned well-known parameters are encountered, the key of the map will be 'unassigned/0x...', where '...' is the hex value of the unassigned parameter. If a parameter has No-Value the value in the map will be null.

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String WAP_PUSH_RECEIVED_ACTION = "android.provider.Telephony.WAP_PUSH_RECEIVED";

Update #2

I have figured out how to pass extras in a PendingIntent to be received by a BroadcastReceiver: Android PendingIntent extras, not received by BroadcastReceiver

However, the extra gets passed to the SendBroadcastReceiver not the SMSReceiver. How can I pass an extra to the SMSReceiver?

Update #3

Receiving MMS

So after doing more research I saw some suggestions of registering a ContentObserver. That way you can detect when there are any changes to the content://mms-sms/conversations Content Provider, consequently allowing you to detect incoming MMS. Here is the closest example to get this to work that I have found: Receiving MMS

However, there is a variable mainActivity of type ServiceController. Where is the ServiceController class implemented? Are there any other implementations of a registered ContentObserver?

Sending MMS

As for sending MMS, I have come across this example: Send MMS

The problem is that I tried running this code on my Nexus 4, which is on Android v4.2.2, and I am receiving this error:

java.lang.SecurityException: No permission to write APN settings: Neither user 10099 nor current process has android.permission.WRITE_APN_SETTINGS.

The error gets thrown after querying the Carriers ContentProvider in the getMMSApns() method of the APNHelper class.

final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Carriers.CONTENT_URI, "current"), null, null, null, null);

Apparently you can't read APNs in Android 4.2

What is the alternative for all those applications which use mobile data to perform operations (like sending MMS) and don't know the default APN setting present in the device?

Update #4

Sending MMS

I have tried following this example: Send MMS

As @Sam suggested in his answer:

You have to add jsoup to the build path, the jar to the build path and import com.droidprism.*; To do that in android, add the jars to the libs directory first, then configure the project build path to use the jars already in the libs directory, then on the build path config click order and export and check the boxes of the jars and move jsoup and droidprism jar to the top of the build order.

So now I no longer get the SecurityException errors. I am testing now on a Nexus 5 on Android KitKat. After running the sample code it gives me a 200 response code after the call to

MMResponse mmResponse = sender.send(out, isProxySet, MMSProxy, MMSPort);

However, I checked with the person I tried sending the MMS to. And they said they never received the MMS.


Source: (StackOverflow)

Send SMS in android

I want to send sms.

What is the intent for SMS sending...or any other code? I want to show compose sms view with my pre-define text passing over in message field.

Is there any help for that?


Note...

this question pre-dates the "SmsManager" era on Android.

For 2014+ simply use SmsManager http://developer.android.com/reference/android/telephony/SmsManager.html


Source: (StackOverflow)

Can we delete an SMS in Android before it reaches the inbox?

I am deleting an SMS from the inbox but I want to know: How can I delete it before it reaches the inbox?


Source: (StackOverflow)

How to send SMS in Java

What are the possible ways to send and receive sms from java application ?

Note: I am expecting a list of possible ways. also your opinion about each, which is better / how?


Source: (StackOverflow)

Android – Listen For Incoming SMS Messages

I am trying to create an application for monitoring incoming SMS messages, and launch a program via incoming SMS, also it should read the content from the SMS.

Workflow:

SMS sent to Android device self executable Application Read the SMS information

If any one can help me!


Source: (StackOverflow)

How to delete an SMS from the inbox in Android programmatically?

On Android phones SMS messages registered to applications also get sent to the device's inbox. However to prevent clutter, it'd be nice to be able to remove application specific SMS messages from the inbox to reduce the potential overflow of those messages.

Questions on other Google groups on getting a definitive answer on a programmatic way to delete SMS messages from the Android inbox don't seem to be pressing.

So the scenario:

  • Android App startup.
  • register SMS message types X,Y and Z
  • messages P,Q,X,Y,Z stream in over the course of time, all deposited in inbox
  • Android application detects receipt of X,Y,Z (presumably as part of the program interrupt event)
  • process X,Y,Z
  • Desirement!!! X,Y,Z are deleted from the Android inbox

Has it been done? Can it be done?


Source: (StackOverflow)