Does two activity in the same package belong to the same thread? - android

I have two activities under the same package (the main activity and another one). Sometimes i need to start the other activity with startActivityForResult. I have two questions:
Does the two activities belong to the same thread?
If i load a native library in the main activity, can i access the native methods from the other activity?
Regarding question 2, suppose there is a native method called NativeMethod1(). In the main activity, as usual, i have the following declaration:
public native void NativeMethod1();
and in the native code i would have a function properly declared (using Java_com_mypackage_myapp_ etc ..). I have added a similar declaration for the other activity, and, in the native library, i added a corresponding method declaration as well. All is working fine, but i fear i am assuming something that it is not always true. This would results in unpredictable crashes.

I wouldn't add native methods into your Activity class. Instead, create a singleton class that you can use from all activities.
Now as far as threading is concerned, yes the UI model for Android is single threaded (aka main thread or UI thread) so all your activities are running on the main thread.
Do not block the UI thread when you are doing long running operations as this will result in an ANR (Activity Not Responding) case, so if you are doing something fancy in your native methods you are better of using an AsyncTask or a Service or come up with your own background threading model.

Related

Using context in an AsyncTask via a Fragment that has no UI

I have previously had my App working with just activities and am now working on converting to fragments in order to improve the UI.
Previously my Activity started an AsyncTask and passed in itself to be used as the Context when certain methods required it (not UI operations, but calls to shared preferences and content providers). I have now learnt that this approach can lead to undesirable outcomes if the Activity is destroyed and garbage collected, but it did compile and run fine.
I began this change because I wanted to make my loading screen behave better when the app was paused and stopped. I realised people frown on loading screens in Android but for me it is required as I have an operation that will take 20 seconds or so and that needs to be completed before the app will function.
So using this guide, I began improving my app.
In short the guide moves the AsyncTask into a Fragment that does not have an attached UI, with a separate Fragment for displaying the loading screen with ProgressBar. This means that the Fragment that spawns the AsyncTask does not have a Context, meaning I cant pass one in to the AsyncTask.
As I said before I have operations in the AsyncTask that require a Context object, so where can I get it from? Should I just pass in that data to the AsyncTask before I start?
As far as I know, the context is not a static property, so you actually need one object to retrieve it.
Thus, you can either go the "hack-way" as in this post:
Static way to get 'Context' on Android?
or you can follow Android guidelines and use a Service for your background loading. Remember that AsyncTask is an utility class designed to help in background operations that later need to communicate with the UI, so you should use AsyncTask in correlation with a UI object.
If you, instead use a Service, then you got no problem, since the Service object itself is the context that you need.
If your AsyncTask is not handling any UI components you can use the parent Activity's context. So where you previously passed in this you'll now pass in getActivity(). Note, if you do have it changing the ui this will set you up for Null Pointer Exceptions.

Controlling a spawned Thread from multiple activities in Android

I have an application that runs a background thread which periodically performs a task. The UI thread moves through several different activities.
The tutorial I used can be found at this blog, the gist of it is the following:
Create a class that extends Thread
public final class JSONThread extends Thread {
Define a method in this class that adds a task to the MessageQueue, prompting executing when able.
public synchronized void enqueueJSON(final JSON.JSON task) {
However, after creating the initial object in my main activity, navigating to another activity obviously loses the Object bound to my Thread. I am no longer able to call methods on that Object (hence unable to add to queue).
I am unsure if this is caused by a wrong decision in architecture on my part or by overseeing the obvious solution. Any ideas? Note that I am trying to avoid AsyncTask for this purpose, since a pool of five threads for a simple task seems a little too much.
You need to store a Thread object as member of some other object with lifetime longer than Activity.
Two ideas for you:
a) It could be a member of Application (http://developer.android.com/reference/android/app/Application.html)
You may have problems with this, if you don't have a Service running. There is no guarantee that your application won't be killed (as example if any system dialog will pop up on top of your activities)
b) It could be a member of Service
(http://developer.android.com/reference/android/app/Service.html)
You should be using a service, not a thread. A service will remain in the background so long as there is an activity bound to it, and it won't be reset when an activity exits.

Calling method of applicationobject in AsyncTask

in my project I have several activities and 1 application defined. The application object contains some methods some of the activities are using.
Within the activity I am calling the methods of the application object out of an inner class that extends AsyncTask. Is this correct resp. is the method of the application is also executed in the AsyncTask process?
Thanks a lot!
Neo74
It depends on where you are calling that method in the Asynctask.
on "doInBackground" everything you are doing will be run on a separate thread.
and on "onPreExecute/onPostExecute" will be run on the main thread(or UI thread).
The application process along with all the threads will run as long as the system is not going to kill it.
You can read more about the process life cycle here:
http://developer.android.com/guide/components/processes-and-threads.html#Lifecycle

run task when activity starts

How can i run an async task when an activity starts? there are about 7 activities, and i need to run the async task, every time one starts, and cancel it when the activity dies.
public MyApp extends Application{
public void onCreate(){super.onCreate();}
}
One obvious way would be to put it in onCreate of every activity, but that is not very DRY. Is there any other way? If I put it in the Application onCreate, then I am unable to execute, Toast.makeText, since I guess no activity is available...
First of all your Code uses the onCreate-Method of the Application Class. In general you should avoid doing stuff here, but use your Activity class. You should be aware of the difference between Application and Activity and should have a good understandig of the Activity-Lifecycle because this are Android fundamentals.
For common tasks to all Activities you should create your own probably abstract BaseActivity , implement common/shared stuff there and inherit from this class. But keep in mind, that several Activities might be instantiated at the same time, so the right handlers to use really depend on what kind of behavior you want to achieve. Again: Understand how the android life-cycle works and how activities are managed or you might run into some trouble.
Have you considered creating a service to host your task, and binding it in each of your activities' OnCreate ?

Dealing with threads

What is the proper way to manage threads working in the background?
For example, I have Activity that creates several threads. I need to do following:
1) Destroy all threads when Application is destroyed
2) Pause threads created within Activity if user navigate away from Activity
3) Destroy threads created within Activity if Activity is destroyed
The only thing that come to my mind would be to have all threads variables declared as public the to be able to issue t.destroy() or something similar on these events that I listed above.
First, I am not sure if this is right way at all, and secondly, I don't like it because I will have to change code to make sure I can reference all threads I created.
For example, I have situation where my Activity instantiate new object (ex. LoadImages.class) and that objects creates several thread depending on how many images is to be loaded. The threads are not visible from the calling activity.
So, do I have to pass threads references to calling activity, or there is some way to know who is the parent of the thread and destroy only thread with particular parent Activity?
For LoadingImages I think there is a simple solution: have a public method on LoadingImage called release that will allow it to release its own resources.
If each of your activities is destroying its own threads, I don't see the need for your step 1.

Categories

Resources