Activity background processing

by skyhigh » Sun, 18 Apr 2010 08:26:44 GMT


Sponsored Links
  was reading the Android "Application Fundamentals" page located at
http://developer.android.com/guide/topics/fundamentals.html#actlife
and found this interesting information in the "Multitasking" section:

"Note that when you write an activity, you can make it stop or
continue running when it is moved to the background (see onStop() in
Activity Lifecycle). For activities that download data from the
network, it's recommended to let them continue downloading so the user
can multi-task."

As far as I was aware I had to create a service if I wanted to have a
background activity such as a media player, internet download, or
processing of data in files on the SD card continue when the activity
was no longer in the foreground.

I went and reread the onStop information on the "Activity Lifecycle"
page, which was referred to. But I didn't find any mention of how an
activity might continue to run in the background after onStop was
called.

The "Activity and Task Design Guidelines" page at
http://developer.android.com/guide/practices/ui_guidelines/activity_task_design.html
also mentions something similar when it says:

"In addition, not all activities have the behavior that they are
destroyed when BACK is pressed. When the user starts playing music in
the Music application and then presses BACK, the application overrides
the normal back behavior, preventing the player activity from being
destroyed, and continues playing music, even though its activity is no
longer visible as a visual substitute, the Music application places
a notification in the status bar so the user still has an easy way to
get to the application to stop or control the music. Note that you can
write an activity to stop when its screen is no longer visible, or to
continue running in the background the latter was chosen for the
music player."

Is the information on these pages accurate? Is there some mechanism
that I have missed to keep an activity running while it is in the
background?

I have been re-reading all this documentation because I currently use
services to perform these types of background functions, and I have a
cooresponding activity screen from which the user started the
background processing and where the user can see the progress and
status of the background service activity.

When the service has finished I need the user to be able to return to
the activity where they started the background activity. I currently
have the service use a notification with an intent to start the
activity, but that requires that the notification intent for the
activity have the FLAG_ACTIVITY_NEW_TASK flag and ends up creating
another instance of the activity rather than returning to the one that
is already waiting in the background. This has the additional problem
that the new instance is on a new task and so the back button and/or
calling Activity.finish() does not return back to the activity the
user came from prior to starting the activity that initiated the
background processing.

If the user stays on my activity screen while the background service
processing is running everything works fine. But if they press the
home key and do some other tasks, getting back to the correct activity
stack from the service notification icon is the area where I am not
understanding how to bring that existing activity stack back to the
foreground.

As far as I can tell t



Activity background processing

by Mark Murphy » Sun, 18 Apr 2010 08:54:57 GMT


 kyhigh wrote:

Let's ignore activities, services, and the like for a moment.

Your Android application, at its core, is an instance of a Dalvik VM,
inside a process, with a thread and a message queue.

The thread blocks on that queue, pops off a message if there is one
there, and takes action based on that message (called "dispatching" back
in the bygone era of Win16 programming).

Some of those messages will cause an activity to be created (e.g., an
activity Intent for your activity is received). Some of those messages
will call callbacks into your code (e.g., onCreate() of an activity,
onCreate() of a service, onClick() of a View.OnClickListener).

As components like activities and services get destroyed, they are
(hopefully) garbage collected and no events pertaining to them will ever
get onto the queue. When there are no more components running, Android
can shut down the rest of the application scaffolding and mothball the
process/VM for later reuse.

This, however, only deals with the main application thread. You can have
other threads, that you fork yourself or that are forked for you (e.g.,
AsyncTask thread pool). Those threads do not have a message queue
(unless you heave a Looper at 'em) and can do whatever you want.

So, is there a case where "an activity might continue to run in the
background after onStop was called"? That depends on how you define
"run" and "activity". Your own threads will continue to run after
onStop() is called. If you wish to consider those threads as being part
of some activity, so be it. The main application thread will not be
calling into your activity while it is stopped.

Personally, I prefer to have my threads either be totally "fire and
forget" with an AsyncTask, or else be managed by a Service, because of
all the joys from dealing with activities coming and going (e.g., screen
rotation). But, that's just me.


Looking at the code, it would appear they use a service.


Off the cuff, I am not certain that is possible.


FWIW, the music player (MediaPlaybackService) uses an Intent with the
Intent.FLAG_ACTIVITY_CLEAR_TOP flag. I'm not sure that will help you,
but I figured I'd mention it, since I'm looking at that code now.

--
Mark Murphy (a Commons Guy)
http://commonsware.com | http://twitter.com/commonsguy

Android App Developer Books: http://commonsware.com/books

--


Sponsored Links


Activity background processing

by skyhigh » Thu, 22 Apr 2010 13:24:14 GMT


  did finally get the notification icon to successfully return to my
activity which started the service with the activity stack intact.

In the manifest file I defined a new task affinity that is used for
all the activities related to this part of the application.

The two activities from the activity stack that are most relevant are
the root "Library" activity, and the "AddAudioFilesProgress" activity
that the service is trying to get back to using a pending intent. In
the manifest file these activities are now defined as:

<activity
android:name="com.amblingbooks.player.Library"
android:label="@string/book_list"
android:taskAffinity=":library"
android:clearTaskOnLaunch="false"
android:alwaysRetainTaskState="true"
android:allowTaskReparenting ="true"
android:launchMode="singleTop" />

<activity

android:name="com.amblingbooks.player.AddAudioFilesProgress"

android:label="@string/activity_add_audio_files_progress"
android:taskAffinity=":library"
android:clearTaskOnLaunch="false"
android:alwaysRetainTaskState="true"
android:allowTaskReparenting ="true"
android:launchMode="singleTop" />

One thing that was not intuitive and which I still don't understand
was that if I set the launchMode of the root "Library" activity to
singleTask, then when the notification icon is used to start the
pending intent for the "AddAudioFilesProgress" activity, the activity
stack gets cleared and I end up looking at the "Library" activity.
When I switched the launchMode of the root activity to singleTop
suddenly my activity stack was left intact and I was getting back to
the "AddAudioFilesProgress" activity, with the activity which had
started it still included in the activity stack. The launchMode of
the root activity changed the behavior which all the other activity
settings (like clearTaskOnLaunch=false and alwaysRetainTaskState=true)
did not seem to effect.

I still don't fully understand the way the Android manages
activities. My application currently has 26 activities in the
manifest file and there are not any of them which should ever have
multiple instances running. The default Android behavior of starting
a new instance of an activity for each new intent doesn't work well
for me. It makes me wonder what percentage of applications really
want to have all those duplicate instances running. The
singleInstance and singleTask launch modes are the only ones that are
described in the documentation as not starting multiple instances,
however the singleInstance launch mode does not support an activity
stack, and the singleTask launch mode has unwanted side effects like
clearing my entire activity stack when using a pending intent from a
notification icon. This behavior was especially confusing because the
intent that was being launched was the "AddAudioFilesProgress" intent
which was not the root activity, but the sta



Other Threads

1. Content Length -1 in HTTP Response / Parial Read

Hi,
  1. Implemented an application, that does a webservice call to our
servers. when the response size is around 200 Kb, iam receiving the
content length as -1. It works well in Droid/ADP1/etc (receiving the
original length) but fails in HTC My Touch and HTC DREAM.

  2. When i replace, the content length , with 200000 , when the
content length is -1. Still, cannot able to read the complete chunk
from the input stream.

This issue can be in other devices too.
The issue could be with the buffer size/allocation ?



Here is that piece of code:
 private byte[] doHttpRequest(String url,String req) throws
IOException {
        InputStream is = null;
        HttpURLConnection c = null;
       OutputStream os = null;

                String errMsg = null;
                try {

                        c = (HttpURLConnection) new URL(url)
                                        .openConnection();

                        c.setDoInput(true);
                        c.setDoOutput(true);
                        c.setConnectTimeout(15000);
                        c.setReadTimeout(40000);
                        c.setRequestMethod("POST");
                       c.setRequestProperty("Content-Language", "en-US");
                       os=c.getOutputStream();
                       os.write(("mobile_request=" +
StringStuff                                                     
.URLEncodeStr(req).getBytes());
                        rc = c.getResponseCode();
                        if (rc != HttpURLConnection.HTTP_OK) {

                                throw new IllegalResponseCodeException("HTTP 
response code: "
                                                + rc);
                        }
                        is = c.getInputStream();
                        int len = (int) c.getContentLength();
                        // Length=-1 , incase of HTC DREAM/HTC Touch
                        if (len > 0) {
                                int actual = 0;
                                int bytesread = 0;
                                byte[] data = new byte[len];
                                while ((bytesread != len) && (actual != -1)) {
                                        actual = is.read(data, bytesread, len - 
bytesread);
                                        bytesread += actual;
                                }
                                return data;
                        }
                }
}

-- 

2. Accessing the /data folder

I'm working on a android project and we're wondering if there is any
way to access all the data on the "/data" folder. I'm asking this
because we need to copy (and paste) all the data on that folder and,
so far, we couldn't find a way to do that.

I know that normally we don't have access due to security (with access
we could modify/read anything that other apps uses), but is that
anyway (signing the app with a Recognized Certificate Authority to
have full access, like we can with J2ME) to have this kind of "power"?

Once more, I don't care with the files inside this folder, I just need
to copy and paste it (I don't care if it's encrypted, for example).

Thalisson.

PS: I heard that with a rooted device I could have access to that
folder, but this is not something that we can use (we can't ask the
customer to root their cell phones :P)

-- 

3. android development and multiple carriers

4. Android UI questions

5. Tapee deee

6. Testing software rendering

7. Do Android chrome Webkit have a plan about supporting Xpath?