RunOnUiThread inside loop efficiency - android

Is it fine to do following if we think about efficiency?
new Runnable() {
#Override
public void run() {
try {
final Runnable uitask = new Runnable() {
public void run() {
//sth that modifies UI
}
};
for (...) {
context.runOnUiThread(uitask);
Thread.sleep(...);
}
} catch (Throwable t) {
}
}
}
I'm most concerned about that runOnUi might create new thread each time, which would be very bad? Am I right or it smarter like ThreadPool?

Well, runOnUiThread doesn't create new threads, it is starting your runnable on the existing UI thread.
but instead of your code you could just do
void onCreate(..) {
...
mHandler = new Handler();
}
for (...) {
mHandler.postDelayed(uitask, DELAY * i++);
}

I'm most concerned about that runOnUi might create new thread each
time, which would be very bad?
Well. It depends what you want to achieve. In Android, native threads are not much efficient. There are more effective ways how to do background work (SDK provides them).
If you want to do some periodical work you can use Handler to achieve your goal. Just create only one Runnable and then you can send request for periodical callbacks. Another solution is to use Services which run in background. They're directly designated for long-running tasks and provide very handy way for background processing.
Sometimes you need to inform user with some information about current progress in your tasks so in this case you can simply use mentioned Handler or AsyncTask.
I think your solution is not clean and efficient. If you'll create for example 40 Threads, your work won't be faster or more efficient at all. Your GB will scream and application will take the greater part of CPU and high battery consumption is something you shouldn't allow.

Related

Android sequential execution of functions

I know Android UI is not really meant for executing functions and waiting for them to finish, however, I think there are use cases were it is required, like networking.
My problem is, I want to run a series of network operations that rely on each other and take a bit more time than the split second it takes to the next execution, so some waiting is in order:
Start hotspot
Get network interfaces and IP
Start socket
Initially I tested that all is working using buttons, then it waited between my button presses. But now I'd like to automatize it. I googled but all I found are solutions with Async task, which is deprecated. I tried with threads and join, but that usually causes weird crashes in the runnable, and it is not very elegant. I wonder if there is another solution?
The best thing you can do with SDK it's use Executors to run your work in background sequentially
val newSingleThreadExecutor = Executors.newSingleThreadExecutor()
newSingleThreadExecutor.execute {
// 1...
}
newSingleThreadExecutor.execute {
// 2...
}
But if you want to touch the UI from background should create handler check if view's not null
val handler = Handler(Looper.myLooper()!!)
newSingleThreadExecutor.execute {
handler.post {
view?.visibility = View.GONE
}
}
How about something like this?
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startHotspot();
getNetworkInterfaceAndIP();
startSocket();
}
}, 300);

Android: what are the pros and cons of using a CountDownTimer vs Thread.sleep()?

What I want to do:
I am wanting to use a worker-thread to regularly update a textfield in the UI Thread. Let's say, every 2 seconds for 30 seconds. I need the 30 second countdown to happen even if the app is not on the foreground. For now, I am evaluating the merits of two different approaches (both using worker-threads) in implementing this. I won't post the full code here to simplify things and also because I am not asking to find any problem in my code. Both solutions work fine.
Solution #1 - use Thread.sleep() inside a for loop
for (int i = 30; i > 0; i-=2) {
Message msg = mHandler.obtainMessage(MSG_ID, i, 0);
msg.sendToTarget();
try {
Thread.sleep(2000);
} catch(Throwable t) {
// catch error
}
}
Solution #2 - use CountDownTimer
Looper.prepare()
new CountDownTimer(30000, 2000) {
public void onTick(long millUntilFinish) {
int seconds = (int)(millUntilFinish);
Message msg = mHandler.obtainMessage(MSG_ID, seconds, 0);
msg.sendToTarget();
}
public void onFinish() {
// left blank for now
}
}.start();
Looper.loop();
My Question
While both work, I am wanting to know if there is a "better" or a "preferred" way to do it for whatever reason. I am thinking there may be areas particularly in battery life but also in performance, accuracy or code design where one solution is better than the other.
What I have done so far to answer this question
My own evaluation so far from reading this SO question and CountDownTimer's documentation are that since both are executed on the worker-thread, both have no ANR possibility. Both solutions will also gaurantee that one "update" will happen only after the previous update has finished. Unfortunately, this is all I have and hoping if anyone can help or guide me to an insightful and/or similar SO question I may have overlooked or was unsuccessful in finding.
I write this question a bit cautiously as I don't have a problematic code which requires debugging but I think this falls within SO's category of a "specific programming problem", which hasn't been answered, and not included in the list of off-topic answers.
1.Calling Thread.sleep pauses the thread execution for a while where as countdown timer actually uses callbacks to notify timer expiry events and is asynchronous in nature.
2.If the thread execution pauses, you will not be able to use that specific thread for any other operation until the sleep timeout hence it is not recommended to use Thread.sleep approach. Obviously there is a load on cpu if it has to resume the thread execution and pause it.Where as in the case of countdown timer the thread continue to be in execution/idle state and as when events occur it fires to the respective listeners.
call Thread.sleep() method is not good idea beacuse ii sleep the UI Thread and disadvantage of CountDownTimer is, It Will stop when ur screen is off hence instead of this two try Handler for that like this
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run()
{
if (dataReceived)
{
cancelHandler();
}
}
};
handler.postDelayed(runnable, 100);
}
public void cancelHandler()
{
handler.removeCallbacks(runnable);
}

Do process repeatedly in the background?

in the beginning I thought it would be fairly simple, but I guess it's not.
I want to call a URL every 10 minutes, either when the app is in the background or
in the foreground. How can I realize this?
I'd use a Service with a Handler inside. Using directly Threads is another approach but it's more likely it will be killed if the Android OS needs to free memory.
The Handler part would be something like this:
boolean stopHandler = false;
Runnable runnable = new Runnable() {
#Override
public void run() {
// Do whatever you need
...
if (!stopHandler) {
handler.postDelayed(this, 600000); // 10 minutes
}
}
};
In iOS 7 you can schedule background operations for periodically fetching data from the network. This tutorial is an example of scheduling background fetch operations -

Android terminating a thread created through runnable

Let's say in various points in my application, I create and fire off a new runnable like so:
new Thread(new Runnable() {
public void run() {
while(true) {
//do lots of stuff
//draw lots of stuff on screen, have a good ol time
//total loop processing time abt 1250-1500ms
//check for conditions to stop the loop, break;
} } }
Now, is there any way to terminate that thread midway through execution other than break; inside my while loop? I'd like to be able to kill it specifically and immediately from the parent thread, like, as in the event that the user just requested to load a different map. It feels clunky to insert an if (stopFlag) break; (set in parent thread) after every 5 or so lines of code.
I peeked at Runnable's and Thread's methods and I just can't see it. Someone know an awesome trick?
You may use AsyncTask and call cancel to cancel the thread.
Instead of while (true) you may check for a condition or a flag that would be changed properly when the Thread/Runnable should be stopped. This seems to be the suggested strategy since Thread.stop() has been deprecated.
You could use AsyncTask as suggested, which probably works best in this case. I believe you can also use the interrupt() method, which is preferred if good if you're not in Android, but still suffers from having to explicitly check if it is interrupted:
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
// do some stuff
if (isInterrupted()) {
break;
}
}
});
t.start();
// Whoa! Need to stop that work!
t.interrupt();

Android 2.2: How can you write a helper method to have your app 'sleep' for N milliseconds?

I need to write a helper method which I can use in various places in the app to essentially make it 'sleep' for N milliseconds.It looks like Handler.postAtTime may be one way to do it, but I'd like any code snippets if available.
You did not say why you need your app to "sleep".
Assuming you need to run a task after some time:
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
// do something here
}
}, 1000); // 1000 ms delay
If you don't mind blocking the thread, an alternative to Thread.sleep() is SystemClock.sleep().
Benefit is that it's a one-liner, as it ignores the
InterruptedException so you don't need to handle it.
More info on http://developer.android.com/reference/android/os/SystemClock.html.
As already stated, you should avoid calling this on the main UI thread as it will cause your app to become unresponsive and potentially show the dreaded dialog we all hate to see (please wait or force close.)
Are you looking for something like this?
try {
//Put the thread to sleep for the desired amount of time (milliseconds)
Thread.currentThread().sleep(1000);
}
catch(InterruptedException ie){
}
This will put the thread you are calling it from to sleep for the amount of time you specify.

Categories

Resources