Sunday, March 27, 2011

Send SMS in Alarm Service at a pre-defined time

In former exercises, it have been shown how to "Send SMS using android.telephony.SmsManager" and "A simple example of Alarm Service, using AlarmManager".

It's a exercise merge them together, start a alarm service in a pre-defined time (10 second), and send SMS using SmsManager inside service when time reached.

Send SMS in Alarm Service at a pre-defined time

In the main activity, data can be passed as bundle as normal.
But there are no getIntent().getExtras() in Service class! It can be retrieved in onStart() call-back method, it will be passed as parameter.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Enter Phone Number:"
   />
<EditText
   android:id="@+id/smsnumber"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:inputType="phone"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Enter Phone SMS Text:"
   />
<EditText
   android:id="@+id/smstext"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<Button
   android:id="@+id/startalarm"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Start"
   />
<Button
   android:id="@+id/cancelalarm"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Cancel"
   />
</LinearLayout>


main activity AndroidAlarmSMS.java
package com.exercise.AndroidAlarmSMS;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AndroidAlarmSMS extends Activity {

 String smsNumber, smsText;
 private PendingIntent pendingIntent;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       final EditText edittextSmsNumber = (EditText)findViewById(R.id.smsnumber);
       final EditText edittextSmsText = (EditText)findViewById(R.id.smstext);
      
       Button buttonStart = (Button)findViewById(R.id.startalarm);
       Button buttonCancel = (Button)findViewById(R.id.cancelalarm);
      
       buttonStart.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    smsNumber = edittextSmsNumber.getText().toString();
    smsText = edittextSmsText.getText().toString();
    
    Intent myIntent = new Intent(AndroidAlarmSMS.this, MyAlarmService.class);
    
    Bundle bundle = new Bundle();
             bundle.putCharSequence("extraSmsNumber", smsNumber);
             bundle.putCharSequence("extraSmsText", smsText);
             myIntent.putExtras(bundle);
    
    pendingIntent = PendingIntent.getService(AndroidAlarmSMS.this, 0, myIntent, 0);
    
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

             Calendar calendar = Calendar.getInstance();
             calendar.setTimeInMillis(System.currentTimeMillis());
             calendar.add(Calendar.SECOND, 10);
             alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
         
             Toast.makeText(AndroidAlarmSMS.this,
               "Start Alarm with \n" +
               "smsNumber = " + smsNumber + "\n" +
               "smsText = " + smsText,
               Toast.LENGTH_LONG).show();
    
   }});
      
       buttonCancel.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
    Toast.makeText(AndroidAlarmSMS.this, "Cancel!", Toast.LENGTH_LONG).show();
    
   }});
   }
  
}


the service, MyAlarmService.java
package com.exercise.AndroidAlarmSMS;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.widget.Toast;

public class MyAlarmService extends Service {
 
 String smsNumberToSend, smsTextToSend;

 @Override
 public void onCreate() {
  // TODO Auto-generated method stub
  
  Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
 }

 @Override
 public IBinder onBind(Intent arg0) {
  // TODO Auto-generated method stub
  Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
  return null;
 }
 
 @Override
 public void onDestroy() {
  // TODO Auto-generated method stub
   super.onDestroy();
   Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
 }

 @Override
 public void onStart(Intent intent, int startId) {
  // TODO Auto-generated method stub
  super.onStart(intent, startId);
  
  Bundle bundle = intent.getExtras();
       smsNumberToSend = (String) bundle.getCharSequence("extraSmsNumber");
       smsTextToSend = (String) bundle.getCharSequence("extraSmsText");
  
  Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
  Toast.makeText(this,
         "MyAlarmService.onStart() with \n" +
         "smsNumberToSend = " + smsNumberToSend + "\n" +
         "smsTextToSend = " + smsTextToSend,
         Toast.LENGTH_LONG).show();
  
  SmsManager smsManager = SmsManager.getDefault();
  smsManager.sendTextMessage(smsNumberToSend, null, smsTextToSend, null, null);
 }

 @Override
 public boolean onUnbind(Intent intent) {
  // TODO Auto-generated method stub
  Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
  return super.onUnbind(intent);
 }

}


Modify AndroidManifest.xml to add <service android:name=".MyAlarmService" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.exercise.AndroidAlarmSMS"
     android:versionCode="1"
     android:versionName="1.0">
   <uses-sdk android:minSdkVersion="4" />

   <application android:icon="@drawable/icon" android:label="@string/app_name">
       <activity android:name=".AndroidAlarmSMS"
                 android:label="@string/app_name">
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
           </intent-filter>
       </activity>
       <service android:name=".MyAlarmService" />
   </application>
   <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
</manifest>


download filesDownload the files.

13 comments:

sujata said...

Hi sir,
I tried this application but the code is not executing as per said.The message is not getting sent at all.Pls send some solution.

Android Er said...

hello sujata,

I tried and worked on Nexus One.

- Can you see the Toast "MyAlarmService.onStart() with..." when time reached?

- Can you send SMS using the code in Send SMS using android.telephony.SmsManager

- Which model you use?

Ravi said...

you should take permission in manifest else code works fine and can you plz tell me how to set alarm for different time not repeating alarm.

Hiren Dabhi said...

Hi, this code works fine for me.i want to send SMS to many user at different time so just update the number, message and time,but it doesn't take message and time second time , it execute old message. how to add the messages in queue and it execute at its specific time. Thanks in advance.

Dineshkumar said...
This comment has been removed by the author.
Dineshkumar said...
This comment has been removed by the author.
Dineshkumar said...

This apps works for contact number which i enter first...but when i change the contact number and message text...the apps sends a message to first contact number not the changed contact number..
please say how to send a message at different contact at specified time..

coolSnapZ said...

hello sir,am new to android.. i tried this but couldn run..there is a prob stating "Unable to open stack trace file'/data/anr/traces.txt" in ma eclipse and so din run in ma emulator..
can u pls temme the soln?

Srinivas said...

Hi Sir, I tried to implement for sending Email using AlarmService on above sending sms code but i cant able to get send please give code for sending Email also

Anonymous said...

hello smsNumberToSend = (String) bundle9.getString("extraSmsNumber"); is null how i will fix it?

karthick said...

Hi,
I tried your code,but its not working for me,even is not showing any error also.while giving number and text message and i am clicking the set button it has to send sms sir,But that toast message is alone showing ,you set the time like that.I added all the permission also.

Terry Markle said...

Code Developer of AndroidAlarmSMS,

I copied your code for each class, layout and manifest into Eclipse. Next, I uploaded the APK file to my Samsung Note3 and ran the program. Everything worked OK.

I tried a second, third and fourth use of the program and changed the phone number and message and clicked on Start.

The new phone number and message was displayed (Toast) by the AndroidAlarmSMS class.

However, the original (1st use) phone number and message was displayed (Toast) by the MyAlarmService class. In addition, the SMS message was sent to the original phone number (1st use) and not the new phone number.

I checked all the code and nothing was incorrect.

What is wrong? Please help me figure out a resolution. Thanks.

Terry

Phu Nguyen said...

Hi, I try run code and its working, but if edit message and resend, it will send old message. Can you fix? Thanks.