Home » Source Code » Android SMS, Handler, Runnable and Service

Android SMS, Handler, Runnable and Service

maninwest
2015-02-13 03:10:01
The author
View(s):
Download(s): 2
Point (s): 1 
Category Category:
AndroidAndroid JavaJava

Description

Translated by maninwest@Codeforge Author:Safak Tarazan@CodeProject
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 Go ogle 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 MainActivity.
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

   

   

       

   

   

   
   
   

B) MainActivty.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


Here, we are creating our Intent object and initializing it by context and the class that we want to activate.
We set a flag to our intent (Intent.FLAG_ACTIVITY_NEW_TASK) object so thattrollService.class will not be created if it is already there. Likely, there is another flag calledFLAG_ACTIVITY_MULTIPLE_TASKand if we would use this flag, ourtrollService.classwill be created although there is atrollServicerunning.
By using the methodputExtra, 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.
We are starting the service by using the methodstartService(trollIntent)which takes an intent object. Likely, we may start some Activities by usingcontext.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.
To stop an Activity or a Service we are using:

contex.stopService(Intnet)
context.stopActivity(Intent) 

         
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, ourMainActivitywill be like this:
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

What is Runnable and Handler?
Runnableobject can be considered as a command that can be sent to the message queue for execution,handlerobject is there to help theRunnableobject to sent this command to the queue.
Our Service Class
Here, to send a message, we create ourSmsManagerobject and using the method ofsentTextMessage, we initialize the message content by taking the data from intent usingintent.getExtra().
Then, we create aRunnableobject 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 thatRunnableobject is responsible for writing the method inside itself to queue and handler sets this writing time sequence periodically so that SMS is sent periodically.
 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


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.
Try to write by yourself instead of running my demo code here.
As you see, flags are really important, take a close look at them.
For more powerful applications, try to get the information from developer.android.com.
References


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

File list

Tips: You can preview the content of files by clicking file names^_^
Name Size Date
.classpath364.00 B2013-03-09 18:57
.project843.00 B2013-03-09 18:57
org.eclipse.jdt.core.prefs177.00 B2013-03-09 18:57
AndroidManifest.xml1.20 kB2013-03-09 19:02
AndroidManifest.xml1.20 kB2013-06-20 14:03
BuildConfig.class347.00 B2013-06-29 16:57
R$attr.class343.00 B2013-06-30 15:48
R$drawable.class410.00 B2013-06-30 15:48
R$id.class553.00 B2013-06-30 15:48
R$layout.class406.00 B2013-06-30 15:48
R$menu.class400.00 B2013-06-30 15:48
R$string.class473.00 B2013-06-30 15:48
R$style.class434.00 B2013-06-30 15:48
R.class634.00 B2013-06-30 15:48
MainActivity$1.class1.75 kB2013-06-29 16:57
MainActivity$2.class1.17 kB2013-06-29 16:57
MainActivity.class1.34 kB2013-06-29 16:57
trollService$1.class2.06 kB2013-06-29 16:57
trollService.class1.87 kB2013-06-29 16:57
classes.dex437.27 kB2013-03-09 19:03
android-support-v4-3b71ba158b1b91642bb31e8ac62ba6eb.jar146.26 kB2013-03-09 18:57
annotations-62bab95d6948a2db17bbc7976160b014.jar943.00 B2013-03-09 18:57
ic_launcher.png6.15 kB2013-03-09 18:57
ic_launcher.png2.12 kB2013-03-09 18:57
ic_launcher.png3.22 kB2013-03-09 18:57
ic_launcher.png9.85 kB2013-03-09 18:57
resources.ap_25.85 kB2013-03-09 19:03
SmsBomp.apk177.39 kB2013-03-09 19:03
BuildConfig.java161.00 B2013-06-20 14:03
R.java1.83 kB2013-06-30 15:48
ic_launcher-web.png46.73 kB2013-03-09 19:00
android-support-v4.jar376.65 kB2013-03-09 18:57
proguard-project.txt781.00 B2013-03-09 18:57
project.properties562.00 B2013-03-09 18:57
ic_launcher.png4.36 kB2013-03-09 19:00
ic_launcher.png1.80 kB2013-03-09 19:00
ic_launcher.png2.41 kB2013-03-09 19:00
ic_launcher.png6.76 kB2013-03-09 19:00
activity_main.xml1.55 kB2013-03-09 18:59
activity_main.xml219.00 B2013-03-09 18:57
strings.xml220.00 B2013-03-09 18:57
styles.xml695.00 B2013-03-09 18:57
MainActivity.java1.74 kB2013-03-09 18:59
trollService.java1.91 kB2013-03-09 18:58
...

Comments

(Add your comment, get 0.1 Point)
Minimum:15 words, Maximum:160 words
  • 1
  • Page 1
  • Total 1

Android SMS, Handler, Runnable and Service (922.01 kB)

Need 1 Point(s)
Your Point (s)

Your Point isn't enough.

Get 22 Point immediately by PayPal

Point will be added to your account automatically after the transaction.

More(Debit card / Credit card / PayPal Credit / Online Banking)

Submit your source codes. Get more Points

LOGIN

Don't have an account? Register now
Need any help?
Mail to: support@codeforge.com

切换到中文版?

CodeForge Chinese Version
CodeForge English Version

Where are you going?

^_^"Oops ...

Sorry!This guy is mysterious, its blog hasn't been opened, try another, please!
OK

Warm tip!

CodeForge to FavoriteFavorite by Ctrl+D