Execute a function without blocking the application android? - android

How to call and execute a function without blocking the application android (this is the location function).
I know I must use the thread but I do not know how, I hope to have a code ready.

Use the following to run code on a separate (non-UI) Thread:
new Thread(new Runnable(){
public void run(){
//do stuff here
}
}).start();
This creates a new Thread (and corresponding Runnable which contains the code to be run inside its run() method ) and starts it -- calling the code in the Runnable.
Alternatively, you could look into AsyncTask (more info here) which avoids using Threads directly.

Related

Why Android myActivity.runOnUiThread and uihandler.post hangs my UI?

I have a method invoked by onClickListener
#Override
public Object getData() {
Thread t = new Thread(new testThread());
t.start();
return false;
}
it start the new Thread well, but when I am trying to do both:
private class testThread implements Runnable{
#Override
public void run() {
OuterClass.this.myActivity.runOnUiThread(new Runnable(){ ... });
OuterClass.this.myActivity.uiHandler.post(new Runnable(){ ... });
...
nothing happens. UI hang up and no Runnable never run (I see it during careful debugging).
Why? Everything should work or even if it fail, why the UI hangs??
Please help!
SOLVED!!! The problem was in method which invokes getData (outside the scope), it never finished failing into infinite loop. Since that scheduled Runnables never started as I think. Now everything works .
AsyncTask is better. It is easier to use, you don't have to manually manage so many threads, and it keeps your code clean.
The doInBackground() method will do your lengthy task on an alternate thread. If you want to update your UI when the task is running, use the publishProgress() method, and if you want to update the UI after the work is done, use onPostExecute().
As to your question on why the UI hangs, see if you are using any method that takes very long or blocks for some reason in the runOnUiThread() method. If any code takes time, remove it from this method.

Android runOnUiThread not async

I've got this piece of code:
public void updateOptionLists() {
Log.d("UI", "Called update");
if (updating){
return;
}
updating = true;
runOnUiThread(
new Runnable() {
#Override
public void run() {
updating = false;
updateOptionList();
scrollToLastTapped();
Log.d("UI","Updating");
}
});
Log.d("UI", "Posted update");
}
What I'd expect from logcat would be something like this:
Called update
Posted update
Updating
As far as I know runOnUi should be asynchronous, right? And considering that the functions called alter the views, which takes a while, this should be running asynchronous. Right?
So I look at my logcat:
Called update
Updating
Posted update
Why does this happen? And how do I make sure this runs asynchronous?
runOnUiThread will execute your code on the main thread, which (in this example) also appears to be where it's called from. This explains the ordering of the log statements you see - all code is executing on a single thread, so is synchronous per the documentation (my emphasis):
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.
runOnUiThread is typically used to execute code on the main thread from a different (i.e. background thread). The use of this separate background thread is what will make a task asynchronous. Calling back to the UI thread at the end of that task is required if you want to modify UI with the results of your background thread calculations.
Android provides several mechanisms for doing work on a background thread and then posting back to the main thread (not all use runOnUiThread explicitly for the latter operation). Good things to read up on include Thread, Handler, AsyncTask, Service, etc.
As far as I know runOnUi should be asynchronous, right?
runOnUiThread, as the name states, runs on UI thread, which is a main thread of an application. It runs synchronously with other code running within that thread and asynchronously with code in other threads.
The word 'asynchronous' has no meaning without a context: some code can run asynchronously with other parts of the code, which means these parts of the code run in different threads. Saying that something 'should be asynchronous' makes no sense without this kind of context.
is updateOptionLists running on the UI Thread?
If this is the case, i would expect this behavior to be ok.
In a normal case you use runOnUiThread from a background thread to come again to the Ui Thread..
Because you call upadetOptionLists() on ui prosess, upadetOptionLists() and runUiThread() both run in the same thread.
To separte theam you need run content in other new thread as following
public void updateOptionLists() {
new Thread(new Runnable() {
#Override
public void run() {
Log.d("UI", "Called update");
if (updating){
return;
}
updating = true;
runOnUiThread(
new Runnable() {
#Override
public void run() {
updating = false;
updateOptionList();
scrollToLastTapped();
Log.d("UI","Updating");
}
});
Log.d("UI", "Posted update");
}
}).start();
}
For accessing the view, you must be in the UI Thread (the main one). So, runOnUiThread will be executed on it.
You must do the long work in an other thread and only call runOnUiThread for little thing like changing a color or a text but not to calculating it.
From the documentation:
Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Multi Threaded Programming: Theory vs Actual
Puppy Photos Explain is the Best pic.twitter.com/adFy17MTTI— Cian Ó Maidín (#Cianomaidin) 6. april 2015
But joke aside.
If you want to test how the threads work in correlation, try:
runOnUiThread(
new Runnable() {
#Override
public void run() {
updating = false;
updateOptionList();
scrollToLastTapped();
Thread.sleep(100);
Log.d("UI","Updating");
}
});

Handler Does Not Execute Run

This feels like it should be a very simple task but I am having a lot of problems with it. In my program I have extended the WebView class for my own and am trying to add it to a layout programatically. Here is my code:
Looper.prepare();
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
MyWebView webView = new MyWebView(context,1,2,3,4);
appState.projectWebView.add(webView);
addView(webView);
}
});
When I run this code it does not execute. I have no idea why. Thanks for you time.
You cannot create a Handler outside of an UI thread. Well, you can, but you will have to turn that thread into a message queue with much more than just Looper.prepare().
What you need to do is pass an Activity to the class that contains the code in your sample, and call runOnUiThread() on it. Alternatively, you can pass a Handler created on a UI thread, for instance create it at the thread that runs your Activity UI, and then call post on that handler.
Note that this is awful advice, you seem to be trying to do things against the Android framework. But, without further information of what you are actually trying to do, there is no much that can be said.

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);
}
});

Runnable run() method called twice sometimes?

I am a new Android developer. I am using the Handler class to schedule some operations. So I am creating runnable objects that calls some of my instance methods.
But I have a problem. Sometimes my run() method in Runnable object is called twice.
What could be the problem??
and there is the code
//deneme is a Handler.
deneme.postDelayed(new Runnable() {
#Override
public void run()
{
randomOyna();
//the instance method that I call.
}
}, 1000);
If don't schedule your Handler to run on another Thread than the UI-thread, there might be a hidden delay in the execution because your Runnable will also run on the UI-thread and thus will only be allowed to run when there is "time" for it. With this hidden delay, it might seem like it is run twice but in reality it's just and over-delayed running before a regular delayed Runnable.
Can't see a mistake just by looking the hint you gave us... But you might try plain old java to run threads instead of handler... Good luck...
Look here for more details

Categories

Resources