Version 1.3
Copyright © 2011 Lars Vogel
19.03.2011
Revision History | ||
---|---|---|
Revision 0.1 | 07.03.2011 | Lars Vogel |
created | ||
Revision 0.2 - 1.3 | 08.03.2011 - 19.03.2011 | Lars Vogel |
bug fixed and enhancements |
Table of Contents
A service is a component which runs in the background, without interacting with the user.
The Android platform provides a lot of pre-defined services, usually exposed via a Manager class. In your activity you access services via the method getSystemService().
Own Services must be declared via the "AndroidManifest.xml". They run the main thread of their hosting process. Therefore you should run performance intensive tasks in the background .
The Android platform provides a lot of pre-defined services, usually exposed via a Manager class. In your activity you access services via the method getSystemService().
Own Services must be declared via the "AndroidManifest.xml". They run the main thread of their hosting process. Therefore you should run performance intensive tasks in the background .
You can declare your own service to perform long running operations without user interaction or to supply functionality to other applications. A activity can start a service via the startService() method and stop the service via the stopService() method. If the activity want to interact with the service it can use the bindService() method of the service. This requires an "ServiceConnection" object which allows to connect to the service and which return a IBinder object. This IBinder object can be used by the activity to communicate with the service.
Once a service is started its onCreate() method is called. Afterwards the onStartCommand() is called with the Intent data provided by the activity. startService also allows to provide a flag with determines the lifecycle behavior of the services. START_STICKY is used for services which are explicit started or stopped. Services started with START_NOT_STICKY will end automatically after the onStartCommand() method is done. A service is started within the main thread of the application therefore all long running tasks should be performed in the background .
A Services needs to be declared in the "AndroidManifest.xml" via a <service android:name="yourclasss"> </service> and the implementing class must extend the class "Service" or one of its subclasses.
One common case is that the service and the activity are very closely related. In this case class just case the IBinder to the class the service provides. See Local Service Example for an example.
Another example would be the usage of Remote Messenger Service. In this case activities can send messages to the service and receive messages as well if they register for them.
Once a service is started its onCreate() method is called. Afterwards the onStartCommand() is called with the Intent data provided by the activity. startService also allows to provide a flag with determines the lifecycle behavior of the services. START_STICKY is used for services which are explicit started or stopped. Services started with START_NOT_STICKY will end automatically after the onStartCommand() method is done. A service is started within the main thread of the application therefore all long running tasks should be performed in the background .
A Services needs to be declared in the "AndroidManifest.xml" via a <service android:name="yourclasss"> </service> and the implementing class must extend the class "Service" or one of its subclasses.
One common case is that the service and the activity are very closely related. In this case class just case the IBinder to the class the service provides. See Local Service Example for an example.
Another example would be the usage of Remote Messenger Service. In this case activities can send messages to the service and receive messages as well if they register for them.
A broadcast receiver is a class which extends "BroadcastReceiver" and which is registered as a receiver in an Android Application via the AndroidManifest.xml (or via code). This class will be able to receive intents via the sendBroadcast() method. "BroadCastReceiver" defines the method "onReceive()". Only during this method your broadcast receiver object will be valid, afterwards the Android system will consider your object as no longer active. Therefore you cannot perform any asynchronous operation.
This tutorial will also use a PendingIntent. A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code.
To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
To perform a broadcast via a pending intent so get a PendingIntent via PendingIntent.getBroadcast(). To perform an activity via an pending intent you receive the activity via PendingIntent.getActivity().
We will define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call then our receiver will be notified and log a message.
Create a new project "de.vogella.android.receiver.phone". We do not need an activity. Create the following "AndroidManifest.xml".
Create the following class "MyPhoneReceiver".
If you install your application and receive a call, e.g simulated by the DDMS perspective in Eclipse, then your receiver will be called and lot a message to the console.
Create a new project "de.vogella.android.receiver.phone". We do not need an activity. Create the following "AndroidManifest.xml".
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.receiver.phone" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:name="MyPhoneReceiver"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE"></action> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="9" /> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> </manifest>
Create the following class "MyPhoneReceiver".
package de.vogella.android.receiver.phone; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; public class MyPhoneReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { String state = extras.getString(TelephonyManager.EXTRA_STATE); Log.w("DEBUG", state); if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) { String phoneNumber = extras .getString(TelephonyManager.EXTRA_INCOMING_NUMBER); Log.w("DEBUG", phoneNumber); } } } }
If you install your application and receive a call, e.g simulated by the DDMS perspective in Eclipse, then your receiver will be called and lot a message to the console.
In this chapter we will use the AlertManager and VibratorManager. The VibratorManager will be called by the broadcast receiver which will be called by the AlertManager.
Create a new project "de.vogella.android.alarm" with the activity "AlarmActivity". Create the following layout.
Create the following broadcast receiver class. This class will get the Vibrator service.
Maintain this class as broadcast receiver in "AndroidManifest.xml" and allow the vibrate authorization.
Change the code of your Activity "AlarmActivity" to the following. This activity will create an Intent for the Broadcast receiver and get the AlarmManager service.
Run your application on the device. Set your time and start the alarm. After the defined number of seconds a Toast should be displayed. The vibrator alarm does not work on the simulator.
Create a new project "de.vogella.android.alarm" with the activity "AlarmActivity". Create the following layout.
<?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"> <EditText android:layout_height="wrap_content" android:id="@+id/time" android:layout_width="wrap_content" android:hint="Number of seconds" android:inputType="numberDecimal">></EditText> <Button android:text="Start Counter" android:id="@+id/ok" android:onClick="startAlert" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout>
Create the following broadcast receiver class. This class will get the Vibrator service.
package de.vogella.android.alarm; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Vibrator; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Don't panik but your time is up!!!!.", Toast.LENGTH_LONG).show(); // Vibrate the mobile phone Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(2000); } }
Maintain this class as broadcast receiver in "AndroidManifest.xml" and allow the vibrate authorization.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.alarm" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="9" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AlarmActivity" 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="MyBroadcastReceiver"></receiver> </application> <uses-permission android:name="android.permission.VIBRATE"></uses-permission> </manifest>
Change the code of your Activity "AlarmActivity" to the following. This activity will create an Intent for the Broadcast receiver and get the AlarmManager service.
package de.vogella.android.alarm; 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.EditText; import android.widget.Toast; public class AlarmActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startAlert(View view) { EditText text = (EditText) findViewById(R.id.time); int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); } }
Run your application on the device. Set your time and start the alarm. After the defined number of seconds a Toast should be displayed. The vibrator alarm does not work on the simulator.
The following will demonstrate how to create and consume a service from an activity. The service will periodically fetch data. The service will used by an activity which bind itself to the service. The activity will allow to request the latest data from the service.
Create a new project "de.vogella.android.ownservice" with the activity "ServiceConsumer".
Create a service "WordService" by create the class and the entry in "AndroidManifest.xml".
Change the layout "main.xml" to the following.
Change the activity ServiceConsumer to the following.
Create a new project "de.vogella.android.ownservice" with the activity "ServiceConsumer".
Create a service "WordService" by create the class and the entry in "AndroidManifest.xml".
package de.vogella.android.ownservice; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class WordService extends Service { private Timer timer = new Timer(); private static final long UPDATE_INTERVAL = 5000; private final IBinder mBinder = new MyBinder(); private ArrayList<String> list = new ArrayList<String>(); private String[] fixedList = { "Linux", "Android", "iPhone", "vogella.de", "helpful", "stuff" }; private int index = 0; public void onCreate() { super.onCreate(); pollForUpdates(); } private void pollForUpdates() { timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // Imagine here a freaking cool web access ;-) if (list.size() >= 6) { list.remove(0); } list.add(fixedList[index++]); if (index >= fixedList.length) { index = 0; } } }, 0, UPDATE_INTERVAL); Log.i(getClass().getSimpleName(), "Timer started."); } @Override public void onDestroy() { super.onDestroy(); if (timer != null) { timer.cancel(); } Log.i(getClass().getSimpleName(), "Timer stopped."); } // We return the binder class upon a call of bindService @Override public IBinder onBind(Intent arg0) { return mBinder; } public class MyBinder extends Binder { WordService getService() { return WordService.this; } } public List<String> getWordList() { return list; } }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.ownservice" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".ServiceConsumer" 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="WordService"></service> </application> </manifest>
Change the layout "main.xml" to the following.
<?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"> <Button android:text="Reload Data" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="showServiceData"></Button> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent"></ListView> </LinearLayout>
Change the activity ServiceConsumer to the following.
package de.vogella.android.ownservice; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class ServiceConsumer extends Activity { private WordService s; private ArrayList<String> values; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); doBindService(); values = new ArrayList<String>(); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values); ListView list = (ListView) findViewById(R.id.list); list.setAdapter(adapter); // List<String> wordList = s.getWordList(); // Toast.makeText(this, wordList.get(0), Toast.LENGTH_LONG).show(); } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder binder) { s = ((WordService.MyBinder) binder).getService(); Toast.makeText(ServiceConsumer.this, "Connected", Toast.LENGTH_SHORT).show(); } public void onServiceDisconnected(ComponentName className) { s = null; } }; private ArrayAdapter<String> adapter; void doBindService() { bindService(new Intent(this, WordService.class), mConnection, Context.BIND_AUTO_CREATE); } public void showServiceData(View view) { if (s != null) { List<String> wordList = s.getWordList(); values.clear(); values.addAll(wordList); adapter.notifyDataSetChanged(); } } }
Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
ReplyDeleteDigital Marketing Training in Chennai
Aws Training in Chennai
<a href="https://www.besanttechnologies.com/training-courses/software-testing-training/selenium-training-institute-in-chennai”>Selenium Training in Chennai</a>
Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
ReplyDeleteDigital Marketing Training in Bangalore
digital marketing training in tambaram
digital marketing training in annanagar
digital marketing training in marathahalli
digital marketing training in rajajinagar
Digital Marketing online training
I am really very happy to find this particular site. I just wanted to say thank you for this huge read!! I absolutely enjoying every petite bit of it and I have you bookmarked to test out new substance you post.
ReplyDeletepython training in tambaram
python training in annanagar
python training in velachery
Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
ReplyDeleteBlueprism training in Chennai
Blueprism training in Bangalore
Blueprism training in Pune
Really you have done great job,There are may person searching about that now they will find enough resources by your post
ReplyDeleteData Science training in Chennai
Data science training in bangalore
Data science online training
Data science training in pune
This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.
ReplyDeletejava training in chennai
java training in marathahalli | java training in btm layout
When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.
ReplyDeleteAWS Interview Questions And Answers
AWS Training in Chennai | Best AWS Training in Chennai
AWS Training in Pune | Best Amazon Web Services Training in Pune
AWS Tutorial |Learn Amazon Web Services Tutorials |AWS Tutorial For Beginners
I was totally impressed with your content, keep posting.
ReplyDeleteSelenium Training in Chennai
software testing selenium training
ios developer course in chennai
Digital Marketing Course in Chennai
android development course in chennai
android course in chennai with placement
My developer is trying to convince me to move to .net from PHP. I have always disliked the idea because of the expenses.
ReplyDeletenebosh igc courses in chennai
Excellent blog!!! I got to know the more useful information by reading your blog. Thanks for posting this blog.
ReplyDeleteFrench Language Classes in Mulund
French Training near me
French Coaching Classes in Mulund
French Classes in Mulund West
German Training Institute in Mulund
German Course in Mulund East
Best German Coaching Center in Mulund
Thank you for sharing such a nice and interesting blog with us. Hope it might be much useful for us. keep on
ReplyDeleteupdating...!!
blogify
Guest posting sites
Amazing Post. The choice of words is very unique. Interesting idea. Looking forward for your next post.
ReplyDeleteHadoop Admin Training in Chennai
Hadoop Administration Training in Chennai
Hadoop Administration Course in Chennai
Hadoop Administration Training
Big Data Administrator Training
IELTS coaching in Chennai
IELTS Training in Chennai
SAS Training in Chennai
SAS Course in Chennai
indian whatsapp group links
ReplyDeleteReally great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training
Thank you for an additional great post. Exactly where else could anybody get that kind of facts in this kind of a ideal way of writing? I have a presentation next week, and I’m around the appear for this kind of data.
ReplyDeletedevops online training
aws online training
data science with python online training
data science online training
rpa online training
Nice blog. Can't be written much better. You’re doing a great job. Keep continuing.
ReplyDeleteEnglish Speaking Classes in Mumbai
English Speaking Course in Mumbai
Best English Speaking Classes in Mumbai
Spoken English Classes in Mumbai
English Classes in Mumbai
Amazing Post. Looking for this kind of information for a long time. Thanks for Posting.
ReplyDeleteInformatica Training in Chennai
Informatica Training Center Chennai
Informatica institutes in Chennai
Informatica courses in Chennai
Informatica course
Informatica Training in Velachery
Informatica Training in Anna Nagar
Informatica Training in Tnagar
It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
ReplyDeleteDevops Course Training in Chennai |Best Devops Training Institute in Chennai
Selenium Course Training in Chennai |Best Selenium Training Institute in Chennai
Java Course Training in Chennai | Best Java Training Institute in Chennai
Hello, I read your blog occasionally, and I own a similar one, and I was just wondering if you get a lot of spam remarks? If so how do you stop it, any plugin or anything you can advise? I get so much lately it’s driving me insane, so any assistance is very much appreciated.
ReplyDeleteMachine Learning Training in Chennai | Machine Learning Training Institute in Chennai
Devops Training in Chennai | Devops Training Institute in Chennai
Data Science Training in Chennai | Data Science Course in Chennai
Selenium Training in Chennai | Selenium Training Institute in Chennai
https://vodafonecustomercarenumber.hatenablog.com
ReplyDeletehttps://vodafonecustomercarenumber.hatenablog.com
https://mpcustomercareno.blogspot.com
https://mpcustomercareno.blogspot.com
https://myairtelcustomercarenumber.blogspot.com
https://myairtelcustomercarenumber.blogspot.com
https://thetechgaint.com/du-screen-recorder-mod-apk-premium-for-free-2019-no-watermark/android/roshan-giri/
ReplyDeletehttps://thetechgaint.com/download-filmorago-pro-mod-apk-for-android/android/roshan-giri/'
https://thetechgaint.com/powerdirector-pro-apk-unlocked-aii-feature-2019/android/roshan-giri/
https://thetechgaint.com/kinemaster-pro-mod-apk-no-watermark-unlocked-v4-11-iatest-2019/android/roshan-giri/
"Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
ReplyDeleteDigital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery
"
https://zulqarnainbharwana.com/laurence-fox/
ReplyDeleteHope you guys are well and healthy during this time. Guys if you want to utilise your time to do something interesting then we are here for you. Our institution is offering CS executive classes and free CSEET classes only for you guys. So contact us or visit our website at https://uniqueacademyforcommerce.com/
ReplyDeletethanku so much this information
ReplyDeletevalueking
THANKU SO MUCH THIS INFORMATION
ReplyDeletecs executive
freecseetvideolectures/
Set An Alert For RMB TO USD To Receive An Email When The Exchange Rate Changes. Alternatively, Bookmark The Page And Check Back Here Regularly.
ReplyDeleteaqualudo
ReplyDeleteVery Interesting blog. Thank you for sharing with us.
ReplyDeleteJewellery Billing Software
Jewellery Billing Software
betmatik
ReplyDeletekralbet
betpark
mobil ödeme bahis
tipobet
slot siteleri
kibris bahis siteleri
poker siteleri
bonus veren siteler
XSZ1TM
شركة تنظيف فلل بجازان viJvkBS6kX
ReplyDelete