How would I use a Looper with an asyncTask? - android

How would I use a Looper with an asyncTask?
The doImBackground method is called to programmatically create a TableLayout called MyResultTable. The MyResultTable, in turn, has a handler that is called by onTouch during MotionEvent.ACTION_MOVE.
After getting complaints about using handle inside asynchTask, I decide to run handler on UIThread. But that's causing my onTouch method to have slow response. So my question is, how do I use a looper with an asyncTask?
UIThread code:
activity.runOnUiThread(new Runnable() {
public void run() {
handler.post(mResizeViews);
}
});
My Looper attempt: (not working: blank screen)
protected MyResultTable doInBackground(Void... params) {
Looper.prepare();
MyResultTable table = new MyResultTable(context, other);
Looper.loop();
return tabl;
}

How would I use a Looper with an asyncTask?
You wouldn't.
The doImBackground method is called to programmatically create a TableLayout called MyResultTable.
That is not an appropriate role for doInBackground(). Use doInBackground() for slow things: network I/O, disk I/O, etc. Use onPostExecute() for generating the UI ("a TableLayout called MyResultTable") based upon the data retrieved by doInBackground().
The MyResultTable, in turn, has a handler that is called by onTouch during MotionEvent.ACTION_MOVE.
That does not make much sense. You use a Handler to forward events to the main application thread from a background thread. Your onTouchEvent() is called on the main application thread, and therefore it does not need a Handler.

Related

Attach a runnable to UI thread without using Handler

I will come out straight that this is a assignment question .So I am not looking for a answer but a better answer .
We have a Async Task which takes in three parameters . The progress parameter(i.e 2nd parameter is) is a Runnable .
#Override
public void onProgressUpdate(Runnable ...runnableCommands) {
// TODO -- you fill in here with the appropriate call to
// the runnableCommands that will cause the progress
// update to be displayed in the UI thread.
}
I am able to make calls to this method using publishProgress() in doInBackGround() method.
The challenge is to have this runnable attached to UI Thread. I know that onProgressUpdate() has access to UI thread and we can create a handler to add to message queue . But apparently it is excessive.
Can some guide me to a better way to do this than create a handler
If you have a reference an Activity, an easy way is using the runOnUiThread(Runnable runnable) method. Looking at the source code, it's really easy to see why:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
If you have a reference only to a View, you can use the post(Runnable runnable) method.
The JavaDoc for both states the Runnable will be executed on the main thread.
According to the documentation
onProgressUpdate
This method can be invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running.
You can find a link here AsyncTask
Basically this method already runs on the UI thread. So you dont need any further code (via handelrs or runOnUiThread()).
In your case, you can just directly call run of that Runnable.

Threads And Handlers

My question Is that What is the difference between Thread and Handler
Q1) What are their effects When they are used in 1) Activity 2) Service
Q2) What is difference between them in context with their life span
I am using following codes for them.
1) ---------------------------
final Handler handler = new Handler();
Runnable runnable = new Runnable()
{
public void run()
{
// do somthing
handler.postDelayed(this, 1000);
}
};
runnable.run();
2) ---------------------------
handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
}
};
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
handler.sendEmptyMessage(0);
} catch (InterruptedException e) {}
}
}
}).start();
Handler:
handler is used to do looper thing.that is to perform same task number of time.
handler can be executed on main thread.
about Handler if its used in service it may get stop if phone state change to sleep.
u can update the UI through handler if it used in activity.
Thread:
Thread is used to things on separate than the main thread of an activity.
thread always runs in background even if phone state changes to sleep mode.
u cant update the UI of as its not running on main thread.it can be done using asynctask not using simple java thread.
Q0) What is the difference between a thread and a handler?
A Thread is the same as it always is in programming. Each thread executes a single call to a method and then terminates. Each thread runs in parallel with every other thread. Threads are in short the way you have more than one thing happening at once.
Passing information between threads is notoriously difficult...
A Handler is Android's way of passing a message from one thread to another. Specifically it allows you to pass a set of instructions as a Runnable into a thread for that thread to execute. Typically they are used as a way for a thread to report its result back to the main thread when it's complete.
Q1) What are their effects When they are used in 1) Activity 2) Service
There is no difference between the way these two items behave in a service or an activity in general except that a service can exist in its own process if android is instructed to do so. Threads in different processes can not directly talk to one another. Services are there to share data,functionality and in some cases threads between activities. There is no requirement for them to have their own thread.
The one major point to note is that only the main thread can update the UI (activity).
Also networking specifically can not be done on the main thread. Networking is usually done from within a service so that the results can be shared but this is not necessary.
The limitations around what must and must not be done in the main thread make threading a little tricky, but these limitations are there to help you avoid freezing the UI unexpectedly.
Q2) What is difference between them in context with their life span I am using following codes for them.
Difficult to answer as I don't understand the purpose of your code.
As an example. Android no longer allows you to do any networking on the main thread as this could freeze the UI while it's waiting for the server to respond over a poor wifi connection. To change something on the UI based on something retrieved from the network you must use a thread to do the networking and pass the data back to the main thread to update the UI.
A (doctored) snippet from my code looks like this:
private final Handler handler = new Handler();
#Override
protected void onCreate( Bundle savedInstanceState ) {
// irreverent to the example
super.onCreate(savedInstanceState);
super.setContentView(R.layout.abstract_main_view);
// Here's the example
Thread networkThread = new Thread() {
#Override
public void run() {
// This could take several seconds
final Collection<Player> players = service.lookupAllPlayers();
Runnable uiUpdate = new Runnable() {
#Override
public void run() {
// This is quick, just adding some text on the screen
showPlayers(players);
}
};
handler.post(uiUpdate);
}
};
networkThread.start();
}
In this example:
The handler is created and exists for the duration of this activity. Because this class is constructed by the main thread, the Handler is also. This means that all messages posted to this handler will be executed by main.
networkThread is created and started by the main thread in onCreate. This lives until it has retrieved the data from the network and posted a response back to the main thread. Then it's done.
The Runnable uiUpdate is created by networkThread once all data is retrieved. It does not have a thread associated and so does not execute right away. Instead it is posted back to main using the handler. It is then executed on the main thread and discarded once complete.
One can use a Handler to inform one thread of events from another thread.
Typical usage would be to inform the UI Thread from other threads.
We can not modify UI elements from other threads directly. So we can define a Handler as a member of an Activity instead.
Activities are created on the UI Thread so this handler also is on UI Thread.
So then from another thread we send a message to the Handler. And on receiving the message the Handler modifies some UI elements.

What is the difference between widget post() vs. handler post()?

I have a WebView which I initialize with loadUrl in AsyncTask.doInBackground. I initialize it like below :
webView.post(new Runnable() {
#Override
public void run() {
webView.loadUrl(authURL);
}
});
AsyncTask is executed as last in Activity.onCreate(), the problem is that most of the time webpage does not get loaded, I see white screen. If I replace webView with handler then all is ok. What am I missing here?
Why are you doing this in doInBackground() if it needs to run on the UI thread anyway?
The difference between Hander.post() and View.post() is that Handler will run your code
on the thread the Handler instance was created on (which is not necessarily the UI thread), while View will always run it on the UI thread (because views are bound to it).

Programmatically determine whether the code is executing from the UI thread or not

In my Android app, I am extracting the code to update UI elements into a separate utility package for reuse. I would like my code to be proactive and update the UI differently if the current execution context is from a UI thread versus a non-UI thread.
Is it possible to programmatically determine whether the current execution is happening on the UI thread or not?
A trivial example of what I am looking to achieve is this - my app updates a lot of TextViews all the time. So, I would like to have a static utility like this:
public static void setTextOnTextView(TextView tv, CharSequence text){
tv.setText(text);
}
This obviously won't work if called from a non-UI thread. In that case I would like to force the client code to pass in a Handler as well, and post the UI operation to the handler.
Why don't you use the runOnUiThread method in Activity
It takes a runnable and either runs it straight away (if called from the UI thread), or will post it to the event queue of the UI thread.
That way you don't have to worry about if your method has been called from the UI thread or not.
When you're not sure the code is executed on the UI thread, you should do:
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// your code here
}
});
This way, whether you're on the UI thread or not, it will be executed there.
You can use the View post method.
Your code would be:
tv.post(new Runnable() {
public void run() {
tv.setText(text);
}
});

Android: Posting events to message queue of View

I have the following problem:
My app has a thread that updates the game state. The app needs to make a change to the state of the View object, triggered by this thread.
The documentation for View states that it should only be modified from the UI thread, and that a Handler should be used to place and handle events.
Yet, there is a function post() in View where I can post a Runnable object that will execute in the UI thread without involvement of Handler. Can I not call this function from threads other than the UI thread??
I'm confused!
Yes you can use View.post(). Internally it uses a handler to post the Runnable.
If you want to run some arbitrary code on the UI thread from a background thread, you can use Activity's runOnUiThread():
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});

Categories

Resources