Monday, October 14, 2013

Send sms in background in Android | Send sms after every 5 min in Android | Alarm Manager demo | Hash-map Demo in Android | Broadcast Receiver Demo in Android

Hi Guys,
Today I am sharing code for send SMS in android programmatically, in background after every 5 min. For this I am using Alarm Manager. And you can set any number of contact and message, I am using Hash-map for that. Important steps are given below-



1) Create Hash Map for store phone number and messages.
     static HashMap<String, String> recorArray = null;

2) Create a receiver i.e. name-AlarmReceiver for sending SMS after every 5 min.

public class AlarmReceiver extends BroadcastReceiver {
private final String SOMEACTION = "com.manish.alarm.ACTION";

@Override
public void onReceive(Context context, Intent intent) {

String action = intent.getAction();
if (SOMEACTION.equals(action)) {
/**
* call method to send sms
*/
MainActivity.sendSms();

}
}

}

3) Create a AlarmManager which will send SMS after every 5 min.

Intent intent = new Intent(context, AlarmReceiver.class);
intent.setAction("com.manish.alarm.ACTION");
PendingIntent pendingIntent = PendingIntent
.getBroadcast(MainActivity.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
AlarmManager alarm = (AlarmManager) MainActivity.this
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
500000, pendingIntent);

4) Add  <uses-permission android:name="android.permission.SEND_SMS" /> in manifest.xml.

5) Add receiver in manifest-
  <receiver android:name="com.manish.sendsmsinbackground.AlarmReceiver" >
            <intent-filter>
                <action android:name="com.manish.alarm.ACTION" />
            </intent-filter>
        </receiver>

My Code

1)MainActivity.java-
package com.manish.sendsmsinbackground;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 *
 * @author manish
 *
 */

public class MainActivity extends Activity {

       EditText editTextPhone, editTextMessage;
       Button btnSubmit, btnStart;
       String phoneNumber, message;
       static HashMap<String, String> recorArray = null;
       Context context = MainActivity.this;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              /**
               * get id's fro xml
               */
              editTextPhone = (EditText) findViewById(R.id.editText1);
              editTextMessage = (EditText) findViewById(R.id.editText2);
              btnSubmit = (Button) findViewById(R.id.button1);
              btnStart = (Button) findViewById(R.id.button2);
              /**
               * create object of hashmap
               */
              recorArray = new HashMap<String, String>();
              /**
               * button's onclick listner object
               */
              btnSubmit.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           phoneNumber = editTextPhone.getText().toString();
                           message = editTextMessage.getText().toString();
                           recorArray.put(phoneNumber, message);
                     }
              });

              btnStart.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           System.out.println(recorArray);
                           fireAlarm();

                     }
              });

       }

       /**
        * send sms method
        */
       public static void sendSms() {

              Set<?> set = recorArray.entrySet();
              // Get an iterator
              Iterator<?> i = set.iterator();
              // Display elements
              while (i.hasNext()) {
                     @SuppressWarnings("rawtypes")
                     Map.Entry me = (Map.Entry) i.next();
                     System.out.print(me.getKey() + ": ");
                     System.out.println(me.getValue());

                     try {
                           SmsManager smsManager = SmsManager.getDefault();
                           smsManager.sendTextMessage(me.getKey().toString(), null, me
                                         .getValue().toString(), null, null);
                           System.out.println("message sent");
                     } catch (Exception e) {
                           System.out.println("sending failed!");
                           e.printStackTrace();
                     }
              }
       }

       public void fireAlarm() {
              /**
               * call broadcost reciver for send sms
               */
              Intent intent = new Intent(context, AlarmReceiver.class);
              intent.setAction("com.manish.alarm.ACTION");
              PendingIntent pendingIntent = PendingIntent
                           .getBroadcast(MainActivity.this, 0, intent,
                                         PendingIntent.FLAG_CANCEL_CURRENT);
              Calendar calendar = Calendar.getInstance();
              calendar.setTimeInMillis(System.currentTimeMillis());
              AlarmManager alarm = (AlarmManager) MainActivity.this
                           .getSystemService(Context.ALARM_SERVICE);
              alarm.cancel(pendingIntent);
              alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                           500000, pendingIntent);
       }
}



2)AlarmReciver.java

package com.manish.sendsmsinbackground;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmReceiver extends BroadcastReceiver {
       private final String SOMEACTION = "com.manish.alarm.ACTION";

       @Override
       public void onReceive(Context context, Intent intent) {

              String action = intent.getAction();
              if (SOMEACTION.equals(action)) {
                     /**
                      * call method to send sms
                      */
                     MainActivity.sendSms();

              }
       }


}


3)activity_main.xml

<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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_margin="10dp"
        android:hint="phone number"
        android:ems="10"
        android:inputType="phone"/>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:inputType="textMultiLine"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:text="Submit" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="73dp"
        android:text="Start Timer" />

</RelativeLayout>


4)manifest.xml

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

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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.sendsmsinbackground.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.manish.sendsmsinbackground.AlarmReceiver" >
            <intent-filter>
                <action android:name="com.manish.alarm.ACTION" />
            </intent-filter>
        </receiver>
    </application>

</manifest>



Thanks!



9 comments :

  1. linking to next page using spinner items??

    ReplyDelete
    Replies
    1. what you mean raj? do you want open new page using spinner? if yes please see this snip of code-

      spinnerBlock = (Spinner) findViewById(R.id.spinner_sector);
      ArrayAdapter adapter2 = new ArrayAdapter(this,
      android.R.layout.simple_spinner_item, Constant.blockArray);
      // array you are populating
      adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
      spinnerBlock.setAdapter(adapter2);

      spinnerBlock.setOnItemSelectedListener(new OnItemSelectedListener() {

      @Override
      public void onItemSelected(AdapterView parent, View v, int pos,
      long id) {
      // TODO Auto-generated method stub
      Intent intent = new Intent(A.this, B.class);
      startActivity(intent);

      }

      @Override
      public void onNothingSelected(AdapterView arg0) {
      // TODO Auto-generated method stub

      }
      });

      Delete
  2. i got this.
    suppose if i have 3 spinner items.when i clicked one of the spinner item it should go to next page(activity page).same like remaining two spinner items.how do i do that?

    item1-->activity1
    item2-->activity2
    item3-->activity3

    help ASAP.
    thanku.

    ReplyDelete
  3. thnx for this tutorial buat i have a probléme the sms not sent !! and start timer don't work plz help me for this probléme and thnk u :)

    ReplyDelete
  4. hello, manish, can you help me how to implement onPasswordfailed() method

    ReplyDelete

Note: Only a member of this blog may post a comment.