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.

Downloading files using Service module

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 01-29-2011, 11:59 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default Downloading files using Service module

As discussed in the Services tutorial, some tasks are easier to implement with services than with activities.
In this example we will download an image file with a service and use it for the activity background.
This service can be used to download larger files as well.

The advantage of a service over activity in this case is that the service isn't paused when the application is in the background.

The steps required for downloading a file with this service is to first set the URL and the target file (the downloaded file is written to this file) and then call StartService.
The process global variables are used for passing those values to the service.
Process global variables can be accessed from all modules and are always available (even when the component is paused).

The service then downloads the file. When download completes the service uses CallSub to notify the Activity that the download has completed.
It is possible that the activity is not active when download is complete. In this case CallSub will not do anything. Press on Home button after starting the download to pause the activity.
We are handling this case in the activity resume event. When the activity resumes we check if we were in the middle of a download task. If yes, then we check the service JobStatus global variable which tells us whether the task has finished.

In most cases it is better to let the activity pull data from the service than pushing the data to the activity from the service. This way when the activity is ready it can grab the data and work with it.

If we were to download a large file in the background it is possible that the OS will at some point kill our process to free some memory. This will of course break our download.
To avoid this issue the service calls Service.StartForeground while downloading. This call marks our process as a foreground process. Which means that it is important not to kill it. A status bar notification is also displayed when the service is in this state.
You should be careful not to overuse this method and only call it if it is really problematic for your service to be killed.

When download completes we also check if the activity is currently active. If not we show a status bar notification that notifies the user that download has completed. When the user presses on the notification (by first dragging the status bar downwards) our activity is resumed.

The program is attached.
Main activity:
Code:
'Activity module
Sub Process_Globals
    
Dim image As Bitmap
End Sub

Sub Globals
    
Dim btnDownload As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout(
"1")
    
'check if we already loaded the image previously.
    If image.IsInitialized Then
        Activity.SetBackgroundImage(image)
    
End If
End Sub

Sub Activity_Resume
    
'check if download has finished while the activity was paused
    If btnDownload.Enabled = False AND DownloadService.JobStatus = DownloadService.STATUS_DONE Then
        FinishDownload
    
End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub btnDownload_Click
    Activity.Color = 
Colors.Black
    DownloadService.URL = 
"http://www.basic4ppc.com/basic4android/images/designer1.png"
    DownloadService.Target = 
File.OpenOutput(File.DirInternalCache, "image.png"False)
    
StartService(DownloadService)
    btnDownload.Enabled = 
False
End Sub

Sub FinishDownload
    
'Load the saved image
    If DownloadService.DoneSuccessfully = True Then
        image = 
LoadBitmapSample(File.DirInternalCache, "image.png", _
         
100%x100%y)
        Activity.SetBackgroundImage(image)
    
End If
    btnDownload.Enabled = 
True
    DownloadService.JobStatus = DownloadService.STATUS_NONE
End Sub
DownloadService service:
Code:
'Service module
Sub Process_Globals
    
Dim HC As HttpClient
    
'Activity is expected to set URL
    Dim URL As String
    
Dim Target As OutputStream
    
Dim JobStatus As Int
    
Dim STATUS_NONE, STATUS_WORKING, STATUS_DONE As Int
    STATUS_NONE = 
0
    STATUS_WORKING = 
1
    STATUS_DONE = 
2
    
Dim DoneSuccessfully As Boolean
    
Dim Notification1 As Notification
End Sub
Sub Service_Create
    HC.Initialize(
"HC")
    Notification1.Initialize
    Notification1.Icon = 
"icon" 'use the application icon file for the notification
    Notification1.Vibrate = False
End Sub

Sub Service_Start
    
'URL and Target should be set by the calling module
    Dim request As HttpRequest
    request.InitializeGet(URL)
    HC.Execute(request, 
1)
    JobStatus = STATUS_WORKING
    Notification1.SetInfo(
"Download Service example""Downloading: " & URL, Main)
    Notification1.Sound = 
False
    
'Make sure that the process is not killed during the download
    'This is important if the download is expected to be long.
    'This will also show the status bar notification
    Service.StartForeground(1, Notification1) 
End Sub

Sub HC_ResponseError (Reason As String, StatusCode As Int, TaskId As Int)
    
ToastMessageShow("Error downloading file: " & Reason, True)
    DoneSuccessfully = 
False
    Finish
End Sub

Sub HC_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    
'Asynchronously download the stream
    Response.GetAsynchronously("Response", Target, True, TaskId)
End Sub

Sub Response_StreamFinish (Success As Boolean, TaskId As Int)
    
If Success = False Then
        
ToastMessageShow("Error downloading file: " & LastException.Message, True)
    
Else
        
ToastMessageShow("Download successfully."True)
    
End If
    DoneSuccessfully = Success
    Finish
End Sub

Sub Finish
    
Log("Service finished downloading")
    JobStatus = STATUS_DONE
    
'Notify the activity that the download has finished.
    'It will do nothing if the activity is currently paused.
    CallSub(Main, "FinishDownload")
    Service.StopForeground(
1'Return the service to the "background" (also removes the ongoing notification)
    If IsPaused(Main) Then
        
'The activity is paused. The user is probably busy with some other activity.
        'Notify the user that the download has finished
        Notification1.Sound = True
        Notification1.SetInfo(
"Download Service""Download complete", Main)
        Notification1.AutoCancel = 
True
        Notification1.Notify(
1)
    
End If
End Sub
Sub Service_Destroy

End Sub
Consider using the new HttpUtils instead of this code: http://www.basic4ppc.com/forum/basic...html#post50919
Attached Files
File Type: zip DownloadService.zip (6.9 KB, 690 views)
Reply With Quote
  #2 (permalink)  
Old 01-30-2011, 02:04 PM
ZJP's Avatar
ZJP ZJP is offline
Senior Member
 
Join Date: Dec 2010
Posts: 136
Default

Hello.
Good work. However, downloading the image is too fast to appreciate the use of services. I think the 'Flickr Viewer' example ( http://www.basic4ppc.com/forum/basic...kr-viewer.html ) is more appropriate. A sort of before / after. Think about it if you have time. Thank you.
(Sorry, i like this example )
JP
__________________
Bad English? French user.

Last edited by ZJP : 01-30-2011 at 02:14 PM.
Reply With Quote
  #3 (permalink)  
Old 01-30-2011, 02:19 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

The Flickr Viewer is also not the best example as the user is not likely to leave the activity while the 9 images are downloaded.
You can however change the URL to point to some other larger file instead (and don't assign it as the activity background).
Reply With Quote
  #4 (permalink)  
Old 01-30-2011, 04:15 PM
ZJP's Avatar
ZJP ZJP is offline
Senior Member
 
Join Date: Dec 2010
Posts: 136
Default

Tx.
__________________
Bad English? French user.
Reply With Quote
  #5 (permalink)  
Old 02-14-2011, 08:04 AM
Basic4ppc Veteran
 
Join Date: Sep 2007
Posts: 480
Default

Great, now one for a multipart upload and we are done :-)
Reply With Quote
  #6 (permalink)  
Old 03-26-2011, 08:05 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 15,689
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

Here: http://www.basic4ppc.com/forum/basic...html#post47094
Reply With Quote
  #7 (permalink)  
Old 04-01-2011, 12:17 PM
philgoodgood's Avatar
Junior Member
 
Join Date: Mar 2011
Location: "land of cheese that stinks"
Posts: 14
Default

hello,

very good english Erel, "Google translator" was too happy .... and so do i
__________________
GalaxyS Ginger 2.3.4 JVQ (stock odex) - CF-Root-XX_UNK_JVQ-v3.7-CWM3RFS - Vista 32b
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
Properties module - useful module for working with properties / ini files Erel Code Samples & Tips 2 10-13-2011 09:02 PM
Service Module / Dienstleistungs-Module klaus German Tutorials 0 01-28-2011 07:36 PM
Activesync & downloading wexican Questions (Windows Mobile) 3 08-14-2010 07:52 AM
How would you handle the downloading of large amount of data? moster67 Questions (Windows Mobile) 2 04-16-2009 06:27 PM
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