Click here to Skip to main content
15,867,704 members
Articles / Mobile Apps / Android

Android SMS, Handler, Runnable and Service (new)

Rate me:
Please Sign up or sign in to vote.
4.39/5 (9 votes)
3 Jul 2013CPOL3 min read 34.2K   1.6K   17   4
Sending SMS in a time sequence by using handler, runnable and service

Introduction

In this article, we will talk about the following topics:

  • Passing extra data by Intent and getting this data
  • Start/Stop a service
  • How to use a background service and its registration to AndroidManifest.xml file
  • Handler and Runnable objects

In order to cover these topics, we will create a very simple application that sends lots of SMSs in a specific time sequence.

You may install this app on Google Play.

Background

To understand this article, the reader should know Java and Android platform.

Using the Code

Before you start coding, the structure of the application should be clear in the coder’s mind. For this demo application, we may follow the simple steps shown below:

  • Get the needed information from user such as destination number, time sequence, etc. on the <span style="FONT-SIZE: 10pt; BORDER-TOP: windowtext 1pt; FONT-FAMILY: Consolas; BORDER-RIGHT: windowtext 1pt; BORDER-BOTTOM: windowtext 1pt; PADDING-BOTTOM: 0in; PADDING-TOP: 0in; PADDING-LEFT: 0in; BORDER-LEFT: windowtext 1pt; PADDING-RIGHT: 0in">MainActivity</span>.
  • Pass this information to a service by Intent to handle SMS sent action.
  • Write a handler and runnable to sent SMS periodically.

In this demo, there are 2 classes:

  • MainActivity
  • trollService

1. Getting the Needed Information From User

A) Activity_main.xml

XML
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >
   
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone Number:" />
   
<EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/numberText" />
       
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message :" />
   
<EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/messageText" />
   
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Troll Sequence :" />
   
<EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sqence"
        android:text="15"/>   
   
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/trollBtn"
        android:text="Start Trolling" />
   
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/stop"
        android:text="Stop Trolling" />  
 
</LinearLayout>

B) MainActivty.java

Java
public class MainActivity
extends Activity {
 
            EditText number;
            EditText message;
            Button send;
            Button stop;
            EditText squence;
            
            Context context=this;            
            
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        
                        number = (EditText)
findViewById(R.id.numberText);
                        message = (EditText)
findViewById(R.id.messageText);
                        squence = (EditText)
findViewById(R.id.sqence);
                        send = (Button) findViewById(R.id.trollBtn);
                        stop = (Button) findViewById(R.id.stop);
               
                        send.setOnClickListener(new OnClickListener()
{
                                    
                                    @Override
                                    public
void onClick(View v) {
                                                
                                    }
                        });
                        
                        stop.setOnClickListener(new OnClickListener()
{
                                    }
                        });
            }
}

2. Pass Information to Service by Intent

  1. Here, we are creating our Intent object and initializing it by context and the class that we want to activate.
  2. We set a flag to our intent (Intent.FLAG_ACTIVITY_NEW_TASK) object so that trollService.class will not be created if it is already there. Likely, there is another flag called FLAG_ACTIVITY_MULTIPLE_TASK and if we would use this flag, our trollService.class will be created although there is a trollService running.
  3. By using the method putExtra, first we give the key and then we give its value so that we are able to pass a data to another Service or Activity.
  4. We are starting the service by using the method startService(trollIntent) which takes an intent object. Likely, we may start some Activities by using context.startActivity(Intent) or we may start several activities at the same time as follows: context.startActivities(Intents) in this case, intents is an array of Intent objects.
  5. To stop an Activity or a Service we are using:
Java
contex.stopService(Intnet)
context.stopActivity(Intent) 
Java
Intent trollIntent = new Intent
		(context,trollService.class);
         trollIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         trollIntent.putExtra("Number", number.getText().toString());
         trollIntent.putExtra("Message", message.getText().toString());
         trollIntent.putExtra("Squence", 
         Integer.parseInt(squence.getText().toString()));
         context.startService(trollIntent);

Finally, our MainActivity will be like this:

Java
number = (EditText) findViewById(R.id.numberText);
		message = (EditText) findViewById(R.id.messageText);
		squence = (EditText) findViewById(R.id.sqence);
		send = (Button) findViewById(R.id.trollBtn);
		stop = (Button) findViewById(R.id.stop);   
	   
		send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Intent trollIntent = 
				new Intent(context,trollService.class);
				trollIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				trollIntent.putExtra
				("Number", number.getText().toString());
				trollIntent.putExtra
				("Message", message.getText().toString());
				trollIntent.putExtra("Squence", 
				Integer.parseInt(squence.getText().toString()));
				context.startService(trollIntent);				
			}
		});
		
		stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				Intent trollIntent = 
				new Intent(context,trollService.class);
				trollIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.stopService(trollIntent);				
			}
		}); 

3. Write a Handler and Runnable in the Service Class to Sent SMS Periodically

For more information about the service, please check my other article here.

What is Runnable and Handler?

Runnable object can be considered as a command that can be sent to the message queue for execution, handler object is there to help the Runnable object to sent this command to the queue.

Our Service Class

  1. Here, to send a message, we create our SmsManager object and using the method of sentTextMessage, we initialize the message content by taking the data from intent using intent.getExtra().
  2. Then, we create a Runnable object to write our fun function into queue so that it can be performed. To make it in a specific period, we create a handler and set its time sequence.

You may think that Runnable object is responsible for writing the method inside itself to queue and handler sets this writing time sequence periodically so that SMS is sent periodically.

Java
final Handler handler=new Handler();

          final Runnable r = new Runnable()
          { int i=1;
              public void run()

        {     if(!run)
           return;
          handler.postDelayed(this,
          intent.getExtras().getInt("Squence")*1000);
          SmsManager smsManager =     SmsManager.getDefault();
          smsManager.sendTextMessage
          (intent.getExtras().getString("Number"),
          null,intent.getExtras().getString
          ("Message"), null, null);
          Toast.makeText(getBaseContext(),+i+
          "SMS Sent", Toast.LENGTH_LONG).show();
                   i++;
              }
          };

      handler.postDelayed(r, intent.getExtras().getInt("Squence")*1000);

Conclusion

  1. Do not trust what I said in this article because I might have them wrong, just use this article to be familiar with service, smsmanager, etc.
  2. Try to write by yourself instead of running my demo code here.
  3. As you see, flags are really important, take a close look at them.
  4. For more powerful applications, try to get the information from developer.android.com.

References

  1. http://blog.akquinet.de/2010/04/15/android-activites-and-tasks-series-intent-flags/
  2. http://developer.android.com/reference/android/os/Handler.html

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralMy vote of 5 Pin
cerkeskizi7-Jul-13 21:57
cerkeskizi7-Jul-13 21:57 
GeneralMy vote of 5 Pin
user55832084-Jul-13 19:03
user55832084-Jul-13 19:03 
GeneralRe: My vote of 5 Pin
Safak Tarazan4-Jul-13 21:33
Safak Tarazan4-Jul-13 21:33 
GeneralMy vote of 5 Pin
Evan Kwan3-Jul-13 15:16
Evan Kwan3-Jul-13 15:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.