Does thread die when activity is finished? - java

If i start a background thread, what will happen if the activity that is started from finishes() before the thread terminates. Will the thread terminate as well or will it stay alive?
new Thread(new Runnable() {
public void run() {
while (mProgressStatus > 0) {
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
progressbar.setProgress(mProgressStatus);
}
});
}
}
}).start();

Threads run idependently from their parents. Thread dies when it returns from Thread.run() back to JVM normally or due to an uncaught exception.

For what you know your thread/application can die at any point, any time, a phone crashes to the ground and the battery is off and the last thing you know it's a phone that it's turned off in the quickest possible way.
The Android lifecycle and its management it's complicated and there is no real answer because at Google, when commenting this sort of things, they like the word "automagic" a lot, so they are surely not giving away any internal detail about this, at least not in "plain old english".
There are the first Google IO about Android that talks about this stuff, you can go back on youtube and search for a Google IO talks about the Android lifecycle if you want more details about this.
Anyway keep in mind that Android grants you absolutely nothing about how and how long your app will live, and you have at least to variables to consider: what the OS ( Android ) is doing and what the user is doing, and this 2 things can even be mixed togheter when the user gives an input involving the life of your app that Android needs to handle.

Related

How to terminate a Java process from a different one?

I am making a CSP solver that calculates all the combinatory solutions of a specific problem like this (briefly put):
// Say we are in a Solver class
public void solve() {
// find solution...
}
// This would be in a Problem class
problem.getSolver().solve();
There is a good chance that the resolution process takes a long time to finish, like more than a couple of minutes. So far, when it has been taking so long I have just stopped the process via console.
But eventually I am going to post my application as a web application in a host that allows Java apps (side-question: I have seen I can do it in Google Cloud and I have been told also about AWS; are they good options?). This means I, or the user, cannot terminate the process anymore if it takes too long.
I want to add the funcionality of having the option of cancelling the resolution process at will.
So I would declare a new method in the Solver class that would terminate the process, which would effectively stop the resolution process:
public void stopResolutionProcess() {
// kill the process, therefore, stop the resolution process
}
I cannot just call problem.getSolver().stopResolutionProcess() after the resolution process has already started, because the thread is already running and until that process ends, that method call will never be executed.
So how could I do this? How could a client signal the service hosted in the cloud to terminate a running process?
Put the long running process in a different thread. You can stop it from the main thread if necessary. See:
How to stop a thread by another thread?
Since you haven't chosen a cloud host yet this question is really difficult to answer. Generally speaking you need a synchronization object. Something like
volatile boolean keepRunning = true;
and your method would do
public void stopResolutionProcess(){
keepRunning = false;
}
then in your solve you have to regularly check for that variable
public void solve(){
while(keepRunning){
// doSomething();
Thread.sleep(500);
}
}
Now i use a variable here but that may not be sufficient. In App Engine your application could run in different instances where static variables are not synchronized. You would need a sync object that is accessible to all your solve threads. In App Engine that would be a datastore object that is also cached in the memcache. But you could use Pub/Sub or other mechanisms to propagate the completion of the task. The specifics are tightly coupled to the environment you'll choose to run this on.
Requests for product recommendations are generally off-topic on Stackoverflow. Choose a product for hosting and if you run into trouble return with a more concrete question.

Firing Android Activity methods on separate process at set interval

I am writing my first Android app(allot of fun so far!) and have run into a roadblock. I am using SDK tools 21.1 targeting Android 4.2.
I am trying to set up a system that allows activities to register to invoke a method at set time intervals. I wanted to do this in such a way that the processing of the request would be handled on it's own process to avoid making the UI unresponsive.
I have been doing some reading and have explored a few avenues. First I thought that a service would be a good way to go about this but found a fair bit of information suggesting that was not a good course of action due to the OS being able to kill services indiscriminately.
I'm now looking at using a ScheduledThreadPoolExecutor. I've created this simple class with an overridable method to pass methods around:
public abstract class BaseEvent implements EventListener {
public abstract void onFire(Object... params);
}
I've created this runnable task invoke the method:
public class HeartBeatTask implements Runnable {
private BaseEvent mCallback;
private Object mParams;
public HeartBeatTask(BaseAioEvent callback,Object... params){
mParams = params;
mCallback = callback;
}
#Override
public void run() {
Log.d(LOG_TAG,"Run called");
if(mCallback != null)
{
mCallback.onEvent(mParams);
}
}
}
I'm going to use it like this (inside an Activity)
ScheduledThreadPoolExecutor threadPool = new ScheduledThreadPoolExecutor(1);
BaseEvent callback = new BaseEvent() {
public void onFire(Object... params){
if(params[0] !=null)
{
Context context = (Context)params[0];
Toast toast = Toast.makeText(context, "Task ran", Toast.LENGTH_SHORT);
toast.show();
}
}
};
threadPool.scheduleAtFixedRate(new HeartBeatTask(callback,(this)),0, 5, TimeUnit.SECONDS);
This will execute the task every 5 seconds, although the callback method is only being run once.
I'm thinking that this may not be a good way to do things. My feeling is that I'm overcomplicating things. What I really need is the ability to have something that will execute a method, on a process other than the main thread, and at a set interval, that activities can bind multiple actions to. So, for instance, I may want to have a UI component update after a call is made to a database, and would want that to happen every minute.
Could any tell me if I am on the right track here? Is what I am trying to do a viable way to accomplish my goal? Is there a better approach I could be taking? Any advice or suggestions would be very much appreciated. Thanks!
a few suggestions for an Android beginner.
Don't call it a separate process. Process is a different thing (Google 'Linux process'), you want to call them on a separate thread inside the same process.
ScheduledThreadPoolExecutor IS better than anything else people will suggest you here such as Timers or PostDelayed.
But I think you do have a philosophical error here as to UI updates shouldn't be running on a timed manner but on an event base instead. Once your Db, Disk or Network operation finishes from a background thread you callback to the UI thread to update it immediately.
There`re several tools for that and I'll list a few, point the one I like the best, but let you do some research on each one
Handler: That's basic java way
AsyncTask: Nice framework but doesn't handle screen rotation
Loader: That's my preferred way
I think your approach is a bit complicated. Consider you example
So, for instance, I may want to have a UI component update after a call is made
to a database, and would want that to happen every minute.
I think I will do it this way.
Create a AsyncTask which will update the UI component.
Create a thread which will execute a new AsyncTask and sleep one minute in a while loop.
Start the thread in step 3. at some point.
Interrupt the thread if you don't want the component to be updated.
Example of step 2
while (true) {
try {
new updateTask.execute();
Thread.sleep(60000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Android is a mobile platform and in all honesty each time you want something run, you better consider it separately. You may be killing the battery or using resources for no reason. I begrudge Zedge app everyday for running for no reason in the background at all times. Especially since on CyanogenMod kernel puts WiFi to sleep, while apparently it is currently on.
I am guessing this is more of an exercise and for running tasks at a specified intervals. One-offs, most universal can be done via AlarmManager class. But this may not be the best solution.
For some system wide events there is the BroadcastReceiver class.
While addressing
So, for instance, I may want to have a UI component update after a call is made to a database, and would want that to happen every minute.
Easier done via an Interface really.

why my android project raise CPU usage range from 60% ~ 100%?

Hello I'm making a chat application in android
so overall, I have a service which contains lots of classes and threads.
in my service, i had socket input read class, socket output writer class, and pinger that in summary have 6 threads.
Actually, i'm very new with this problem, well i can say i have no idea what makes a program occupy high percentage of CPU processes. is it cause too many static variables maybe? or too many running threads maybe, or too many local variables maybe?
I don't know exactly what is going on...?
So, please share with me your experiences and knowledge
UPDATE
public void run() {
while(isRunning) {
try {
Thread.sleep(500);
if(!startCheck) {
//Log.v(TAG, "SocketQueue: "+socketTaskQueue.size()
if(socketTaskQueue.size() > 0) {
processSocketTask();// TODO
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
so basically, i made my threads like above example.
so, i have a vector called socketTaskQueue, and this thread job's is to check whether there's a socket task or not. if it does, then it will execute processSocketTask function that will get the top element of the vector queue and then remove it.
UPDATE
T.T this post is embarrassing! i forget to put Thread.sleep() in some of my threads!
SORRY FOR BOTHERING YOU GUYS! :p
It is caused, usually, by threads that use CPU even when they cannot accomplish useful work. For example, when a thread is waiting for something to happen, does it wait in a way that uses no CPU? Or does it keep waking up needlessly even before it can do work?
It can also be caused by threads that do work in extremely inefficient ways.

How to implement background tasks in Android

In my application I need, basically, two tasks performed in the background. One is sync some data with a php server, sending values and updating the local database with the answer periodically and the other is download files requested by the main thread from the server,notifying the UI when the download finish.
I only want do those things while the app is in foreground. And if the users opens another app, finish the current transactions and stop consuming resources.
At this point I'm a little lost about how to implement that. I have never used Services and I really dont know if a service is a valid solution, due to the service is used when you want your code still running when the app goes to background.
Other solution I've thought is to implement some kind of Handler that periodically (20 minutes for example) launches a thread for sync with the server. Lauching a thread also when a download is requested and sending a broadcast at the end.
What about that solution? Is valid? If yes, how can I detect when the app (not an activity) stops beeing at foreground in order to cancell the handler's posts?
Thanks in advance
If you choose the service I recommend you to use an IntentService http://developer.android.com/reference/android/app/IntentService.html
When you implement onHandleIntent you can have a loop that waits for the amount of time you want it to sleep, after it wakes up it can perform the task that you want.
#Override
protected void onHandleIntent(Intent intent) {
while(true) {
yourBackgroundTask();
// Sleep
try {
wait(WAIT_TIME);
} catch (Exception e) {
Log.i(TAG, e.getMessage());
break;
}
}
}

How do you have the code pause for a couple of seconds in android?

Basically I need a pause (based on just a few seconds) to be put into one action so that the user can see what happens before the next action is taken. So for blackjack, when it's the dealer's turn and he decides to hit, he hits, a card is added, and then he decides what to do next. So before he decides on what to do next, I want the code to pause so it can be "seen" as to what the dealer is doing this way the dealer doesn't complete his actions in less than a second and the player only sees the results.
Thanks in advance!
I should note I have tried using wait(insert number here); but i am told by eclipse that it causes a stack interception error or something of the sort and throws an exception, thus doing nothing : (
Well this is interesting, (the way I've programed the things is "interesting" to say the least) I did the Thread.sleep(5000) and threw it under a try catch, it does sleep for 5 seconds and then continues doing the code. However my updates to views don't show until after I press a button(Is really hating event driven programming).
Learning to think in terms of events is indeed the key here. You can do it. :)
The first rule is: never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive. Any work you do there should not block; do what you need to do and return as quickly as possible. Definitely avoid doing I/O on the UI thread. (There are some places where you can't really help it due to lifecycle requirements, for example saving app state in onPause.) If you ever call Thread.sleep on the UI thread you are doing it wrong.
Android enforces this with the "Application not responding" (or "ANR") error that the user sees. Whenever you see this in an Android app it means the developer did something that caused the UI thread to stall for too long. If the device is really bogged down for some reason this error might not actually be the app developer's fault, but usually it means the app is doing something wrong.
You can use this model to your advantage by posting your own events. This gives you an easy way to tell your app, "do this later." In Android the key to posting your own events is in the Handler class. The method postDelayed lets you schedule a Runnable that will be executed after a certain number of milliseconds.
If you have an Activity that looks something like this:
public class MyActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler.postDelayed(new Runnable() {
public void run() {
doStuff();
}
}, 5000);
}
private void doStuff() {
Toast.makeText(this, "Delayed Toast!", Toast.LENGTH_SHORT).show();
}
}
Then 5 seconds after the activity is created you will see the toast created in doStuff.
If you're writing a custom View it's even easier. Views have their own postDelayed method that will get everything posted to the correct Handler and you don't need to create your own.
The second rule is: Views should only be modified on the UI thread. Those exceptions you're getting and ignoring mean something went wrong and if you ignore them your app will probably start misbehaving in interesting ways. If your app does most of its work in other threads you can post events directly to the view you want to modify so that the modifications will run correctly.
If you have a reference to your Activity from that part of your code you can also use Activity#runOnUIThread, which does exactly what the name implies. You might prefer this approach if posting to a single view doesn't really make sense in context.
As for updates to views not appearing until you hit a button, what kind of views are these? Are they custom views that are drawing these updates? If so, are you remembering to call invalidate after data changes to trigger the redraw? Views only redraw themselves after they have been invalidated.

Categories

Resources