After searching for similar questions here on StackOverflow, I've come to the understanding that you cannot run 2 activities simultaneously. Is there any way around this?
I've read about Services and Asynctasks, but I'm still a little bit confused.
I thought Threading/Intents/Handlers would work, but i'm finding that threading is a way to go from one activity to another (please correct me if I'm wrong) and not running two things at once.
Let's say I wanted to combine an android MediaPlayer activity and a video recording activity, while still being able to have the two interact with each other, would it be possible in android? is it possible to have the camera running while having a video play/having a separate activity run within the same application? If so, How?
I found a question here that addresses a similar issue(https://stackoverflow.com/questions/12021518/android-simultaneous-record-and-playback-different-sources), But it is unanswered.
Any suggestions or advice will be greatly appreciated!
Intent ,Handler and Thread are really 3 different things.
An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly. So an intend is used to navigate from one activity to another. (For you example : A camera intent can be used a request to capture a picture or video clip through an existing camera app and then returns control back to your application.)
A Thread must be created to execute long running jobs. If you do not explicitly start it in its own thread then it will run on the main (UI) thread which may be noticeable as jittery or slow to respond interface by your users.
A Handler is very convenient object to communicate between 2 threads (for instance : a background thread need to update the UI. You can use a Handler to post some Runnable from your background thread to the UI thread).
As #krishna has mentioned you can try fragments...
Related
What is the difference between all the above?
I found various posts which were helpful but also quite confusing. According to my understanding in short this is what I came upto:
Threads are tasks that share same resources
Processes are tasks which have independent rersources. A process can
have multiple threads.
Tasks are the instructions being executed
Now this is where I get confused. How is an activity related to all
these three in android. Activity can have multiple tasks so it must be something like a process. But then what is the difference between activity and process. Moreover I read somewhere that tasks are stack of activities. It got me all confused. Ive also read that all activities run on UI thread which just make the distinction a little more confusing.
You should differentiate between Processes & Threads vs. Activities vs. Task. They aren't even really in the same category.
Let's start with the simplest one, Task's. Assuming you are not talking abouy any actual class, i.e. TimerTask, the basic concept of a Task is the following.
When a user starts your app for the first time, a new Tasks is created. You can see this by pressing the "OverviewButton", represented by a Square for the software buttons. (on Android 5.0 an higher)
A Task will not get disposed of, unless the User actually removes(swipes left/right) it from the Overview screen.
So a Task is really just a high-level abstraction for the user.
Like you alluded to, a Tasks has an Activity backstack, which is just a normal stack that is used to keep track of the "history" for the user. For example, your App is launched, your MainActivity will be at the bottom of the stack, the User enters some values and then goes on to a new Activity. Now this new Activity is above the previous one, and the user can press the "back button" at -hopefully- any time to get back to the previous activity.
Now for Processes &Thread's, a Processes under Android is very similar to a linux process, your app will usually only be working within one single process. A process gets assigned a certain part of the memory by the OS, if you're familiar with languages like C, attempting to acess memory that does not belong to your process wil cause a
"segmentation fault".
Like you said, a process may have any number of Threads, assuming the OS can manage the required Overhead.
A process will at least have one Thread, under android this is called Main-Thread or UI-Thread. Threads, very basically, allow you to do some work in parallel. You will most likely need to make use of them, for example when performing network operations.
Now for Activities, they have no direct relationship to multithreading. The currently "active Activity" is the one that is run on the UI-Thread. So all of its callbacks will be run on the UI-Thread, unless specifically documented not to.
An Activity is an abstraction used by the android framework, it exists at a fundamentally different level than a Processes & Thread's. You can call a method defined in a Activity, from any Thread you want.
A really nice question, from my little experience with android development, I'd like to contribute. Let's start from..
Processes
Ever opened task manager on windows to see open apps? Those are processes. On android, when an app is launched, a new process is opened and allocation of memory etc is given.
The activity classes,imports and threads all make a process in the Android system. sometimes you see an error message when an app crashes "unfortunately com.android.bakerapp has stopped."
This means an error causes the whole process of threads, imports, activities to close. So basically processes are parts of an app or an app in general that's running.
Activity
An activity is the heart and soul of all android apps, all Threads, preferences, views and layouts are opened by android activity class. It is the container object that holds views, passes information around and runs threads too. Activities communicate with each other through intents, objects in the class extends and methods.
Activity is the piece of code that creates and communicates UI and everything a user sees and uses. It is used to create threads. Which is discussed below.
Threads
This one is easy, a thread is basically a process to get something done, it lives and dies after its work. Imagine you have an activity with a view of picture on the screen and you want to automatically set your apps theme color to the most common color on the picture using a library.
The best method to do this without the user knowing and also confusing the main thread responsible for loading the picture into a view from a website is to open a thread using an Asynchronous task (something that runs in background) is an example of a thread.
So a thread is basically a life cycle of a task to be done, it can be continuous (Main activity views and list views) or short (Find a dominant color in a picture) or fun and multitasking (downloading a picture from a group chat while at thesame time chatting with your girlfriend on WhatsApp).
Threads are the most essential part of all activities and processes and can send,receive and process data.
Activities cannot work without threads because the setContentview and UI itself is just another thread, you can have multiple threads in one activity.
Happy coding!
https://developer.android.com/guide/components/processes-and-threads.html
I know this is old, but you can also say that a thread is the smallest unit of execution of code. Threads are scheduled to run on the CPU. A process can have one or more threads.
I am currently trying to write a simple application very similar to this:
http://lab.andre-michelle.com/tonematrix
My main problem is that I do not know how to handle the general program flow. Traditionally, I would use a loop inside the main function that handled the drawing and updated the state and everything. The way the android framework works is a bit confusing since the access points into the program are the various onSomething() functions. This is quite confusing for a beginner.
How do I keep track of time and how do I know how when to move to the next square column?
Do I HAVE to use threads? Is there a single thread solution, similar to the single loop approach?
You can use timers, they do already run in their own threads.
You can also use handlers for timed execution.
In case of the sample program u linked to, you would add something with onTouch and have a timer running in the background to periodically play the tune.
The activity lifecycle should be seen as the lifeline of your program not so much of the code in it.
How to keep track of time ?
System.currentTimeMillis();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
I need a good way to get data from a thread to another activity.
I have one gaol: how to develop an Android app that plots bluetooth data forever in real-time.
I inherited a background thread which updates the screen with new data it receives over a bluetooth connection. When I launch my Plot activity I can see a bluetooth background thread continue to write bluetooth data to Logcat forever and ever. So I know for a fact the bluetooth background thread is still running when I launch my Plot activity.
I have succeeded as follows: since this bluetooth background thread seems to run fovever, I decided to use its update() method to call my static Plot.plotData() method to plot the bluetooth data. And this works. It will will run endlessly with out a problem - receiving bluetooth data and plotting it via periodic calls from the bluetooth background method update() to my static Plot.plotData() method.
The latest feedback I have received "It sounds like you're looking for an in-memory way to share data, and that's simply not the way the Android activity model works." In-memory???But this is rediculous. An Android phone has a limited amount of RAM for running Activities (one at a time), threads, handlers, Services, AnycTasks, etc. And an SD card for persisting data.
One critical person basically said: "In order to share data from a bluetooth background thread to my Plot activity (Plot.plotData()) that I must use the SD card." ??? This just sounds nuts, because I have it working using my static method Plot.plotData().
Frankly I don't see anything wrong with my solution primarily because those who criticize it do not follow up with a definitive alternative.
If you find my solution deficient please speak up and provide a definitive solution." Unless I use a new thread, handler, Service, AsyncTask, etc, everyone assumes my solution is not a good one. Why? Supposing the criticism is valid, PRECIOUSLY What should I do instead of what I am currently doing?
One more time: if you have background task running you should create Service. That's how Android expects applications to behave. Otherwise your thread may be terminated at any time (assuming none of the Activities are active).
From documentation:
A service is a component that runs in the background to perform long-running operations or to perform work for remote processes
This precisely describes your case.
Also carefully read Processes and Threads, specifically Process Lifecycle section.
Basically your application falls into Background Process or Empty Process group most of the time. That's why you need Service started in your application.
I'm designing an android app which will need to do the following steps:
user pushes a button or otherwise indicates to "sync data".
sync process will use REST web services to move data to and from the server.
the data will be stored locally in a sqlite database.
the sync process should provide status updates/messages to the UI
the user should not be allowed to wander off to other parts of the application and do more work during the sync process.
The first time the sync process runs, it may take 10-20 minutes.
After the initial sync, less data will be transferred and stored and
I expect the process to take 1-2 minutes or less.
I've been doing a lot of reading about android's AsyncTask and various examples of using a Service ... But I don't fully understand the design considerations and trade-offs of choosing one design over the other. I currently have my demo project stubbed out using an AsyncTask. After watching (most of) Developing Android REST client applications: http://code.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html# I'm left confused the design patterns described here feel overly
complex, perhaps because I just "don't get it" yet.
I come from a java, spring, web and desktop application background. Thinking and designing in terms of a handheld device is quite new to me. (What happens when the screen layout is changed? What happens when the phone rings while I'm running a sync?) Taking 2 steps back, if the initial sync IS going to be such a long running process, is there a better way for me to think about the problem->solution, the user experience, the user expectations of an application running on a phone?
Would love to hear from some more experienced android developers out there who have already wrestled with these questions.
In my opinion this is the most tricky/hard part of a mainstream/average Android development. For instance on BlackBerry this is IN TIMES easier.
Definitely you need to use a Service.
AsyncTask does not suit, because it is tightly "bound" to your Activity via a Context handle (otherwise you would not be able to update UI of the Activity from your AsyncTask). However an Activity can be killed by OS once the Activity went in background. An example reason of going to background can be an incoming call - user switches to Phone application so your Activity becomes invisible. In this case (depending on the current RAM state) OS may decide to kill one of the background (invisible to the user) activities.
Some devs workaround this by arranging a static stuff for having a long-running actions inside of. Some recommend to use Application instance. This is because static stuff and Application exist while the whole app process exists. However those are incorrect workarounds. Processes in Android are also may be killed when OS decides it is time to. Android OS have its own considerations about what it can kill and in what order. All processes are devided to 5 levels of "killability". Here is the doc where those levels are specified. It is interesting to read there:
Because a process running a service is
ranked higher than one with background
activities, an activity that initiates
a long-running operation might do well
to start a service for that operation,
rather than simply spawn a thread —
particularly if the operation will
likely outlast the activity. Examples
of this are playing music in the
background and uploading a picture
taken by the camera to a web site.
Using a service guarantees that the
operation will have at least "service
process" priority, regardless of what
happens to the activity.
Your Activity where users initiate a long-running action should show a ProgressDialog to make sure user does not do anything else while the action is running. The guide is here.
Also, you'd most likely want to use the NotificationManager for notifying the user about your long-running action completion (or failure) if your Activity is currently invisible. Here is the NotificationManager info to start from.
There are multiple considerations that you must weigh in order to best decide how to approach your situation. It sounds like you need a good comparison between the two approaches... So here is a list of similarities, and differences and additional considerations that must be taken into account when working on a handheld device.
A Service is a part of your Application that has no UI. It may be called by a UI(Activity) to be started, or may be started by any other component of your Application. When developing, you have the freedom to place it on a different thread, or even run it in a different Task or Process. This allows you to ultimately separate it from your UI. Additionally, you may start the Service to run independently (startService) or bind your activity to it (bindService) depending upon your needs. By using custom Handlers, you can set callbacks to update the UI with your progress. A Service does not necessarily end if a User changes Activities, but may be ended at ANY time by the OS.
A AsyncTask is always instantiated from the UI thread. It only allows specific callbacks, but simplifies the process of multi-threading for the purposes of relatively short transactions (as compared to dedicated separate threaded services) that are inherently tied to actions performed by an Activity. Whenever a User changes Activities, the AsyncTask is put on "pause" and may even die because there is no UI thread for your Activity any longer.
The thing that I would be most concerned about is if the app is going to take 10-20 minutes the first time, I would ASSUME that the User will either change tasks temporarily or set the phone down until it completes (which can cause all of the same complications if the phone sleeps). Given this consideration, a threaded service bound to your activity may be your best choice. To protect your UI, I would make a Progress Dialog for your Activity that receives your progress callbacks. This limits user input in YOUR app and allows your service to continue the way that it needs to. Then override the Activity onResume to check the status of your Service and if it is running. Then you can reset the Dialog immediately.
Given that this is my preferred method, I would also take into account that the OS may kill the App at any time anyway. So make sure to have some way to detect an incomplete or partial sync. Then you may resume automatically when your Activity or Service restarts.
With AsyncTask if the user goes to another Activity you can't transfer that object to the other Activity so it dies. There are tricks you can play when say the user rotates the screen or something like that, but that doesn't extend to general purpose destruction. AsyncTask can randomly die.
Google Sync is run as a Service in the background because syncing can take a while to complete. You might need to follow their path and create your own sync service that you can communicate with. Here is some thoughts how to accomplish that:
http://mylifewithandroid.blogspot.com/2008/01/about-binders.html
You can definitely communicate between Service and Activity, but it's tricky to do it right.
The choice is mainly dependent on the app design. Since both AsyncTask and IntentService stands their ground, what you may want from the app(user experience) is more important and then choose either or both. Some scenarios are mentioned below (mostly what I experienced while developing apps)
Assume apps that have feeds pages - where more than one api calls are made to make the page presentable ( /getFriends, /getDates, /getPictures etc.) you can warp all such api calls to a single AsyncTask with executor which is multithreaded and the sequence of execution doesn't matter. In contrast to IntentService which runs all calls in sequence in a single worker thread. For a high end device with multi-core the call from AsyncTask is more effective. And if you start the AsyncTask on UI thread then updating IU is a piece of cakes(read less boiler plate code). And even if an user leaves the page, with intelligent use of not holding on to the context the app doesn't crash.
Assuming you are trying to write an app which doesn't need the user to be on view/activity/fragment and the total execution time to show something is not mission critical (assume sync service or user notification/alarm) then IntentService is a better choice. (no hassle to start Asynctask on UI thread so that you don't need to write a Handler to force changes on UI etc. etc. and less boiler plate code)
From my experience - write small app for both and compare the pros and cons to get a better idea. (p.s I'd suggest take a look at the iosched app from google to get a better idea - they use both Asynctask and IntentService)
I tend to prefer the IntentService + BroadcastReceiver combo because they give you a really strong degree of control
You definitely have to make sure the UI is running if you are updating something on the screen. ASyncTask crashes were at once reported to be one of the top causes of Android crashes. This can be avoided by keeping some sort of "activityIsAlive" variable and skipping or delaying a UI update if the activity is dead.
The IntentService + BroadcastReceiver combo is a little more resistant to the crash because most tutorials tell you to shut off the BroadcastReceiver onPause or onStop. If you do not do this, again you'll have to turn off the UI update. There's a runOnUiThread command somewhere that will help you do UI updates.
The IntentService + BroadcastReceiver combo is also more extensible. You can create functions and extend BroadcastReceiver to make a more elegant REST processing solution. However, it does require more plumbing vs an ASyncTask
If you do delay the UI update, you may be able to rig it on OnWindowFocusChangedListener. When that function receives true, it means that the UI is alive.
tldr; Make sure the Activity and/or Fragment is alive before updating the UI if you are running something in the background
2015 Edit: check out Loaders as well. A little harder to grasp because there's a lot going on behind the scenes
I have a question about postDelayed. The android docs say that it adds the runnable to the queue and it runs in the UI thread. What does this mean?
So, for example, the same thread I use to create my layout is used to run the Runnable?
What if I want it as an independent thread that executes while I am creating my layout and defining my activity?
Thanks
Chris
Yes that would run on the UI thread.
If you want to run a background thread then do it the normal way.
Thread t = new Thread(new Runnable(){});
t.start()
But if you want to change the UI at all in response to something that a background thread might do, then you can use postDelayed().
Any changes to the UI must be done on the main UI thread.
Congratulations! You found one of the places where there is more than one solution.
Handlers, and PostDelayed can be nice lightweight ways of having your foreground activity called on a regular basis. Even the messages are reused. These are used in the Snake example program (Snake/SnakeView.java/sleep()) to make the snake move. It runs as 'post a message delayed by 500ms', in 500ms catch it in HandleMessage (the default for Handlers), move, then send it again. Even the message is reused with obtainMessage(). I've used these for making a button update while it is pushed down.
Threads are a bit heavier. You might use these for background or where you are already used to running a thread. Make a 'new Thread(aRunnable).start()'. I haven't used them much on the Android.
Launch an Intent with StartActivityForResult() and catch the result with OnActivityResult to make a standard RPC. See step 2 of the notepad example for more information.
Look into more Intents to launch for different scenarios. I find putting your 'create and launch intent' into separate functions helps maintenance and debugging.
Good luck!