Android – creating simple service

When you look at my posts on this blog, you will, besides few posts about WordPress and Zend find most articles about Symfony2 development.
Well, now things are about to change slightly.
Depending on next project needs and features, I will maybe start to write about Magento platform like other developers here on the blog, but in this transitional times between projects I have to do, let me write about some other platform that I am planning to use and to master knowledge about: Android platform.
This is my first android touches so, please don’t be too strict in comments. Keep in mind that I will do my best! π
So, let’s start.
What is Android service anyway?
“A Service is an application component representing either an application’s desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.”
You guessed, that definitionΒ came from http://developer.android.com/reference/android/app/Service.html.
One more thing about service in Android:
Service is NOT a separate process
Service is not a Thread
Please keep this in mind when trying to develop multithreading application β¦
Let’s get to work.
Assuming that we have created basic android project, here is our activity:
//AndroidservicetutorialActivity.java
package com.inchoo.tutorial;
import android.app.Activity;
import android.os.Bundle;
public class AndroidservicetutorialActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Let’s create simple service:
Create class called FirstService in your namespace, make it extends Service class and Eclipse will guide you to import necessary namespaces and also to add unimplemented methods (onBind):
package com.inchoo.tutorial;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class FirstService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Now we will override two more methods: onStart and onDestroy, so our FirstService class looks like this:
package com.inchoo.tutorial;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class FirstService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
Don’t forget to add this service declaration in your AndroidManifest.xml in order to be set up properly:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.inchoo.tutorial"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".AndroidservicetutorialActivity"
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=".FirstService" ></service>
</application>
</manifest>
Let’s add log to find out when service is started and destroyed and also we will immediately stop service after starting like someone from Google said somewhere: βBe nice to other applications, start your service, do whatever you need to do and then stop the service after thatβ…
Finally out FirstService.java class looks like this:
package com.inchoo.tutorial;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class FirstService extends Service{
private static String TAG = "Inchoo.net tutorial";
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.d(TAG, "FirstService started");
this.stopSelf();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d(TAG, "FirstService destroyed");
}
}
And now it’s time to start it from our Activity (AndroidservicetutorialActivity.java):
package com.inchoo.tutorial;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class AndroidservicetutorialActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, FirstService.class));
}
}
Start your android application and if you look inside LogCat you will find this lines:
Hope this helps someone :-). Cheers.
34 comments
Hi Darko,
Thank you so much for this great tutorial. Very well explained. An old user of your website.
To find mobile app quote for an application project is no doubt a big challenge. Whether, you are looking for develop or design iPhone Apps. Here are six basic principles that will help you to find the best one smartly.
1 β Getting Multiple Bids
2 β You Get What You Pay
3 β Analyze their Experience
4 β Check Out Their Previous Work
5 β Check Out Their Portfolio
6 β Your Search Ends Here!
As of explanation, it looks author reexplains to a programmer beginner, how to implement a method (not service !) in a class or a callback. You implement this, run this and what else ? It will print 2 diagnostic messages and stop and sleep for ever. That you could have achieved in a method implemented in some class. Right ? Why is service implementation so important then ?
Very poor explantions.
Its very Helpful,
Thanks for sharing, many beginners will start from here.
Its very Helpful,
Can I add layout xml file to service? When service is running the layout should on top. Is it possible?
Thanks for helping me to understand basic concepts. As a beginner in Android programming your post help me a lot.
sir I just want to know whether this service will be able to run in background forever even my app is closed or my phone is in sleep mode.
Use Start_Sticky
HI
This was a precise tutorial. Thanks
Hello,
I have problem with a service. I start the service with BroadcastReceiver it checks the state of network if it is connected it dims the screen brightness. When I run the app on mz Tablet with Kitkat 4.4.2 everzthing works great even when I remove app from Recent. On my HTC Desire phone also Running KitKat 4.4.2 everzthing works fine until I remove the app from Recent list then, although he Service still runs the change of network state does not affect the screen brightness. Anyone can help?
Hello,
I have problem with a service. I start the service with BroadcastReceiver it checks the state of network if it is connected it dims the screen brightness. When I run the app on mz Tablet with Kitkat 4.4.2 everzthing works great even when I remove app from Recent. On mz HTC Desire phone also Running KitKat 4.4.2 everzthing works fine until I remove the app from Recent list then, although he Service still runs the change of network state does not affect the screen brightness. Anyone can help?
A good tutorial but my requirement is : Can’t we launch an activity from a service ? If so, will the service keep running in background and the activity in foreground ?
Thanks for the tutorial
I have a question. I have developed Windows services and now want to develop an Android service. I understand how Windows services work and was hoping there are parallels in Android. For example, when I start a service in Windows, it remains running until the system is turned off (or the service is specifically stopped or removed).
Is the same true for Android ? For example, if I develop an app which has an activity with a button. When the button is pressed, it starts the service. If the Activity stops will the service also stop.
If this is so, is there a way of developing a background service that just continues running. I am thinking of a data collector which just continues to run in the background.
Hello,
I have a design problem here.
I am working on a android platform customized for my needs and specifications. I have two external devices which communicates to this platform over UART (send and receive control commands). and there is a protocol to follow to construct the control packets. Now I am stuck with designing HAL and service layer to implement the protocol. and then multiple apps use that service to control the devices.
Will be very great and lucky to get the feed back from you. much appreciate.
Thanks and Regards,
Giri
nice and understandable tutorial π
This was a precise tutorial. Thanks
when i should start my service in seperat process or when not should
Thanks a lot.
Very good tutorial for beginner in services.
Has been depreciated, omit the line.
Thanks…..
it is a big tutorial for learning about service
how to stop the service from activity
how to i check service is available or not in my all activity classes
Thank you, helped a lot! π
plz help me ,how to connect facebook in android . i am trying for that but not run that application.
You can see follow posts for my requirement :
http://stackoverflow.com/questions/4637821/how-to-analyze-incoming-sms-on-android
and
https://github.com/jewel/unnagroid
Sorry, My English is terrible.
I’m new in Android, my problem is: I want to delete incomming SMS with phone number “903823929” immediately any time my phone’s runing. How can i create service for this requirement. I try follow codes but … it’s error.
Please, help me.
There’s source code for “Auto delete incomming SMS” with phone numeber : “903823929”:
private void deleteNags(Context context) {
ContentResolver cr = context.getContentResolver();
Uri inbox = Uri.parse( “content://sms/inbox” );
Cursor cursor = cr.query(
inbox,
new String[] { “_id”, “thread_id”, “body”, “address”},
null,
null,
null);
if (cursor == null)
return;
if (!cursor.moveToFirst())
return;
//int count = 0;
do {
//String body = cursor.getString( 2 );
String adr = cursor.getString(3) ;
if( adr.indexOf( “903823929” ) == -1 )
continue;
long thread_id = cursor.getLong( 1 );
Uri thread = Uri.parse( “content://sms/conversations/” + thread_id );
cr.delete( thread, null, null );
//count++;
} while ( cursor.moveToNext() );
//message( “Deleted: ” + count );
}
And Source code for “Detect incomming SMS”:
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get(“pdus”);
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
// show first message
Toast toast = Toast.makeText(context, "Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
try {
Thread.sleep(10000);
// ????
deleteNags(context);
// ????
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Really awesome. Your step is very much appreciable for new android application developers.
Hello Guys,
I am stuck in a issue where i think you people can help me out,
I am having a site and the app for the same on my iphone.
For the price i have created a attribute which displays the iphone price for only the people who have iphone installed and not on the site.
But when a person checkouts the general price is displayed in the admin sales ,but it should be the iphone price there.
Please help me out.
Till now ,
i have tried to get the condition that if the product has iphone price , then it will overwrite the general price , but i want to limit this condition to app only. Is there any way i could get if the app is being used or the site is being used.
Or any alternate for the above condition. Please help
Regards
Thanks in advance
Thanks.
Precise tutorial for beginner in services.
Haider
You should create at least one main activity from where you will start service, but you dont have to implement the UI.
Great tutorial!!!
I was looking how to start service and
this is the best solution I found.
One question, is it possible for service to be running even if you kill activity or to start just service without activity.
Thanks in advance
Excellent tutorial, thumbs up!
thanks for taking time.
This is the best service tutorial currently on the web!!