Thursday, February 28, 2013

Send SMS from android programmatically in background

Sending SMS in background from android mobile using code.


For sending SMS from android using code follow below code snippet.
It's very easy and simple.

See below link for more update about android

http://www.varemads.com/category/android/

Java Activity for this 

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendsms("******Mobile Number Here******", "***Message Content Here***");
}
});
}

public static void sendsms(String address,String msgContent)
    {
        try
        {
            SmsManager sms = SmsManager.getDefault();
            ArrayList<String> smsString = sms.divideMessage(msgContent); 
            sms.sendMultipartTextMessage(address, null, smsString, null, null);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Xml file 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="92dp"
        android:text="Button" />

</RelativeLayout>


Give this below permission in Android Manifest file.


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



4 comments:

  1. can you tell me how to send using 2nd sim??

    ReplyDelete
  2. You can only send sms if your default sim selected. If have an option that always ask before send you manually select the sim before send.

    ReplyDelete
  3. hey can you give mw the source code ? i want this , pls

    ReplyDelete
  4. Using above code you can create sample demo and test it this is working dude...
    Here in above example one java Activity code and other is xml layout for the same you can create simple example app using above code.

    ReplyDelete