Download the free trial version
Basic4android Video
Features
Tutorials and manuals
Showcase
Screenshots

Go Back   Android Development Forum - Basic4android > Basic4android > Basic4android Getting started & Tutorials
Documentation Wiki Register Members List B4P Search Today's Posts Mark Forums Read

Basic4android Getting started & Tutorials Android development starts here. Please do not post questions in this sub-forum.

Service Modules

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 01-27-2011, 03:03 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default Service Modules

Basic4android v1.2 adds support for Service modules.
Service modules play an important role in the application and process life cycle.
Start with this tutorial if you haven't read it before: Android Process and activities life cycle
Code written in an activity module is paused once the activity is not visible.
So by only using activities it is not possible to run any code while your application is not visible.
Services life cycle is (almost) not affected by the current visible activity. This allows you to run tasks in the background.
Services usually use the status bar notifications to interact with the user. Services do not have any other visible elements. Services also cannot show any dialog (except of toast messages).
Note that when an error occurs in a service code you will not see the "Do you want to continue?" dialog. Android's regular "Process has crashed" message will appear instead.

Before delving into the details I would like to say that using services is simpler than it may first sound. In fact for many tasks it is easier to work with a service instead of an activity as a service is not paused and resumed all the time and services are not recreated when the user rotates the screen. There is nothing special with code written in service.
Code in a service module runs in the same process and the same thread as all other code.

It is important to understand how Android chooses which process to kill when it is low on memory (a new process will later be created as needed).
A process can be in one of the three following states:
- Foreground - The user currently sees one of the process activities.
- Background - None of the activities of the process are visible, however there is a started service.
- Paused - There are no visible activities and no started services.

Paused processes are the first to be killed when needed. If there is still not enough memory, background processes will be killed.
Foreground processes will usually not be killed.

As you will soon see a service can also bring a process to the foreground.

Adding a service module is done by choosing Project - Add New Module - Service Module.
The template for new services is:
Code:
Sub Process_Globals

End Sub

Sub Service_Create

End Sub

Sub Service_Start

End Sub

Sub Service_Destroy

End Sub
Sub Process_Globals is the place to declare the service global variables. There is no other Globals sub like in Activity as Service doesn't support Activity objects.
Sub process globals should only be used to declare variables. It should not run any other code as it might fail. This is true for other modules as well.
Note that Process_Global variables are kept as long as the process runs and are accessible from other modules.

Sub Service_Create is called when the service is first started. This is the place to initialize and set the process global variables. Once a service is started it stays alive until you call StopService or until the whole process is destroyed.

Sub Service_Start
is called each time you call StartService (or StartServiceAt). When this subs runs the process is moved to the foreground state. Which means that the OS will not kill your process until this sub finishes running. If you want to run some code every couple of minutes / hours you should schedule the next task with StartServiceAt inside this sub.

Sub Service_Destroy is called when you call StopService. The service will not be running after this sub until you call StartService again (which will run Sub Service_Create followed by Sub Service_Start).


Service use cases


As I see it there are four main use cases for services.
- Separating UI code with "business" or logic code. Writing the non-UI code in a service is easier than implementing it inside an Activity module as the service is not paused and resumed and it is usually will not be recreated (like an Activity).
You can call StartService during Activity_Create and from now on work with the service module.
A good design is to make the activity fetch the required data from the service in Sub Activity_Resume. The activity can fetch data stored in a process global variable or it can call a service Sub with CallSub method.

- Running a long operation. For example downloading a large file from the internet. In this case you can call Service.StartForeground (from the service module). This will move your activity to the foreground state and will make sure that the OS doesn't kill it. Make sure to eventually call Service.StopForeground.

- Scheduling a repeating task. By calling StartServiceAt you can schedule your service to run at a specific time. You can call StartServiceAt in Sub Service_Start to schedule the next time and create a repeating task (for example a task that checks for updates every couple of minutes).

- Run a service after boot. By checking Project - Service properties - Run At Boot your service will run after boot is completed.

Notifications


Status bar notifications can be displayed by activities and services.
Usually services use notifications to interact with the user. The notification displays an icon in the status bar. When the user pulls the status bar they see the notification message.

Example of a notification (using the default icon):






The user can press on the message, which will open an activity as configured by the Notification object.

The notification icon is an image file which you should manually put in the following folder: <project folder>\Object\res\drawable.

Accessing other modules

Process global objects are public and can be accessed from other modules.
Using CallSub method you can also call a sub in a different module.
It is however limited to non-paused modules. This means that one activity can never access a sub of a different activity as there could only be one running activity.
However an activity can access a running service and a service can access a running activity.
Note that if the target component is paused then an empty string returns.
No exception is thrown.
You can use IsPause to check if the target module is paused.

For example if a service has downloaded some new information it can call:
Code:
CallSub(Main, "RefreshData")
If the Main activity is running it will fetch the data from the service process global variables and will update the display.
It is also possible to pass the new information to the activity sub. However it is better to keep the information as a process global variable. This allows the activity to call RefreshData whenever it want and fetch the information (as the activity might be paused when the new information arrived).

Note that it is not possible to use CallSub to access subs of a Code module.

Examples:
Downloading a file using a service module
Periodically checking Twitter feeds
Reply With Quote
  #2 (permalink)  
Old 01-27-2011, 08:15 PM
Cor Cor is offline
Basic4ppc Veteran
 
Join Date: May 2007
Posts: 481
Default

could you export a simple service app

thanks
__________________
Best regards,
Cor de Visser, Netherlands, HTC Magic 2.2.1

Amazing Guitar Chords for Android
http://android.ready4music.com
Reply With Quote
  #3 (permalink)  
Old 01-28-2011, 09:00 AM
schimanski's Avatar
Basic4ppc Veteran
 
Join Date: Oct 2007
Location: Germany
Posts: 289
Default

Thanks, Erel!!!!

It is one of the most needed things and very easy to use...


@Cor!

Here a very simple program to check a service. It is only a timer, which runs in the backround and updates the label1.text, if the activity-modul becomes active.....You need only an activity-modul with one label and a timer, which updates the label. And a service-modul, which counts in the backround...

Activity-Modul:
Code:
Sub Process_Globals 
   
Dim Timer1 As Timer
   Timer1.Initialize(
"Timer1",1000)
end sub

Sub Button1_Click
  Timer1.Enabled=
True
  
StartService(TestService)
End Sub

Sub Timer1_Tick
  Label1.Text=TestService.Counter 
End Sub
Service-Modul(TestService):
Code:
Sub Process_Globals
  
Dim TimerService As Timer
  
Dim Counter As Int 
  Counter=
0    
End Sub

Sub Service_Create
  TimerService.Initialize(
"TimerService",1000)
  TimerService.Enabled=
True
End Sub

Sub Service_Start
  Counter=Counter+
1
End Sub
...
...
Sub TimerService_Tick
  
StartServiceAt(""DateTime.Now, True)
End Sub
It runs fine on my device and should also count, if the device is sleeping...
__________________
schimanski
--------------------------------------
Device: Motorola Defy, Samsung Galaxy Tab P1000
Dekstop: Asus Eee PC
Reply With Quote
  #4 (permalink)  
Old 01-28-2011, 09:07 AM
schimanski's Avatar
Basic4ppc Veteran
 
Join Date: Oct 2007
Location: Germany
Posts: 289
Default

But, I have one question:

With the following code, I send geo-data to the googelmaps-intent:

Code:

  
Dim Intent1 as Intent

  URI= 
"geo:" & Latitude & "," & Longitude & "?q=" & Latitude & "," & Longitude
  Intent1.Initialize(Intent1.ACTION_VIEW,URI)
  Intent1.SetComponent(
"googlemaps")
  
StartActivity(Intent1)
How is it possible to send updated data from my service to the Intent? I can't find the right syntax for intent1.PutExtra....

thanks for help....
__________________
schimanski
--------------------------------------
Device: Motorola Defy, Samsung Galaxy Tab P1000
Dekstop: Asus Eee PC
Reply With Quote
  #5 (permalink)  
Old 01-28-2011, 09:55 AM
Cor Cor is offline
Basic4ppc Veteran
 
Join Date: May 2007
Posts: 481
Default

thanks,

will try this evening
__________________
Best regards,
Cor de Visser, Netherlands, HTC Magic 2.2.1

Amazing Guitar Chords for Android
http://android.ready4music.com
Reply With Quote
  #6 (permalink)  
Old 01-28-2011, 10:20 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

A small correction about your example.
The ServiceTimer timer is not needed and is likely to fail eventually.
You should instead schedule the next task with StartServiceAt.
Android will eventually kill your process. By scheduling the next task with StartServiceAt you make sure that a new process will be created when the scheduled time arrives. This is not the case with a regular timer.
Also note that for most application 1 second is a very very short period as it will drain the device battery. Running a task once an hour or every 30 minutes is usually more appropriate.

Updated code:
Code:
Sub Process_Globals
  
Dim Counter As Int 
  Counter=
0    
End Sub

Sub Service_Create

End Sub

Sub Service_Start
  Counter=Counter+
1 ' This counting will not work for long. If it is important it should be saved in a file instead of a variable.
 StartServiceAt(""DateTime.Now + 30 * DateTime.TicksPerSecond, True'schedule the next task to run in 30 seconds.
 ... do the required work
End Sub
It is not recommend to start an activity from a service. As the activity will pop up while the user is busy with something else.
Instead you should show a notification. When the user presses on the notification, the activity will start.

I will post a full example on Sunday.
Reply With Quote
  #7 (permalink)  
Old 01-28-2011, 10:40 AM
schimanski's Avatar
Basic4ppc Veteran
 
Join Date: Oct 2007
Location: Germany
Posts: 289
Default

Thanks, Erel for your efforts!

I'm waiting on your example.

My idea is, that i don't want to start an other activity from the service. I only want to update the data in the active-app. I hoped, that there is a way to send only the new geo-data (lat,lon) from my app to googlemaps, when the user had activated the map-software.....

rgds
__________________
schimanski
--------------------------------------
Device: Motorola Defy, Samsung Galaxy Tab P1000
Dekstop: Asus Eee PC
Reply With Quote
  #8 (permalink)  
Old 01-28-2011, 10:42 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

You should check for updates in Sub Activity_Resume. The service for example can put the update in a process global variable or a file.
Reply With Quote
  #9 (permalink)  
Old 01-29-2011, 07:35 PM
Junior Member
 
Join Date: Aug 2008
Location: Guildford, UK
Posts: 28
Default

Hi,

when will 1.2 be available to all?
Thanks
Mike
Reply With Quote
  #10 (permalink)  
Old 01-29-2011, 09:20 PM
Junior Member
 
Join Date: Aug 2008
Location: Guildford, UK
Posts: 28
Default

Sorry, just saw the thread about the beta release.
Mike
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Weather web service using HTTP lost2 Share Your Creations 5 02-14-2012 05:47 AM
Wish: Service Library Kernowquack Bugs & wishlist 4 01-21-2011 09:35 PM
Difference between RSS and Web service Pratibha_Pillai Questions (Windows Mobile) 0 08-03-2009 03:48 AM
How to set a password for a service pallavi Questions (Windows Mobile) 1 01-19-2009 01:36 PM


All times are GMT. The time now is 10:30 AM.


Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0