How to execute application continuously without hangs device in blackberry - java

I have created an application of contacts synchronization. when i run it on device it hangs my device while synchronizing then i am not able to open another application, I am also doing auto synchonization with in a perticular period of time.
I want that synchronization should be perform without hang to device and if i get any interrupt i.e. any call while syncing then it should pause for that moment and continue at call end.
How can i do this ?

I dont know how this is working for Blackberry, but may be an example for Eclipse RCp is helping you.
You have the choice to execute a Runnable between
The thread which calls this method is
suspended until the runnable
completes.
Display.getDefault().syncExec(runnable);
The caller of this method continues to
run in parallel, and is not notified
when the runnable has completed.
Display.getDefault().asyncExec(runnable);
In your case you have to make the decision if you can start the job in asynch mode.
When you ar enot sure, whether your job is executed in asynch mode, you should implement some outputs to the console including timestamp.

Related

I want to run a thread in my application that will run for the entire time while the user is online. I cant choose variant

I want to prevent the thread from stopping during the transition between activities and call this thread during the start of my application. I have one option and I would like to share it. So far, I have stopped at writing an android service in which to include the beginning of the stream that, I need to perform. And then call it in the class inherited from the application class. It is important to note that my thread will send certain data to the database every minute. Perhaps you can advise a more reliable and popular way to solve the problem.
Threads don't stop between Activities. That would be impossible to do safely- threads cannot in general be safely stopped by anyone but the thread itself without risk of data corruption or deadlock. So Android doesn't even try. (You can cancel a thread from another thread, but that works by setting a flag and hoping that the thread you want to cancel looks at it occasionally to honor it.)
The real problem is twofold
1)How do you know if the thread is already running so you don't launch it again. This is solvable in a variety of way.
2)Do you want the thread to work when the app is in the background? This is the real problem, because Android kills background apps regularly, which will end the thread. There is no reliable way to make a thread run constantly in the background in Android. Here your best bets are either a foreground service running to keep the app active, or to not use a thread and make your app even t driven (for example, setting a repeating alarm for every 15 minutes and running then).

Create a system process (ProcessBuilder) reattachable after main process quit

I'm searching for a method to create a Process that keeps running after the main process of my application quit (it already do that) and that i can re-get in another instance of my application (after first instance exit).
I mean a thing like the screens in linux shells but for a java Process.
I don't know if that's possible...
It's not possible. You can't get a Process object for existing processes, nor for processes that aren't children of your process.
screen works by never actually exiting. When you detach from a screen session it continues running in the background, maintaining control over the processes started inside of it. Re-attaching to a session makes it visible again, but it was really running the whole time.

Launch a windows batch file from Java GUI Application

I have created a Desktop Application using Java Swing. It takes some input from user, creates a config file and a batch file to run a python scripts. Many concerns are:
- I want the GUI to be in active mode when the batch file execution in progress
- There is a button like ShowLog in the app to check the console output at during execution. That should work on clicking
- I have a "Task in Progress" kind of message in GUI which should be replaced by "Task is Completed" when batch file execution is done
- A "Stop" button also is there to stop the batch file execution forcefully. That should work fine as well
(Note: The batch file execution will take hours to complete)
Can anybody come up with some ideas how I can achieve all these?
As you seem to be aware, Swing is a single threaded framework, which means that anything that is run within the context of the Event Dispatching Thread will prevent it from updating the screen or responding to user input.
The basic solution would be to use a Thread to run the batch process in, but this raises issues with synchornisation of updates to the UI, as you should never modify or interact with the UI from outside the context of the EDT.
A better solution would be to use a SwingWorker, which provides you with the ability to run long running tasks in the background, but provides you with the ability to publish updates to and process updates within the context of the EDT, it also provides you with a done method which is called after the doInBackground method exits and is called within the context of the EDT.
Finally, it provides you with a cancel option - This, however is where the problem occurs. Presumably you will be reading the input from the process in a secondary thread and will be waiting for the process to exit within the same thread (SwingWorker) you started it. SwingWorker relies on the interrupt funcitonality of Thread which may not trigger the waitFor method to return.
Having now gone a read the Process documentation, waitFor does throw an InterruptedException
if the current thread is interrupted by another thread while it is
waiting, then the wait is ended and an InterruptedException is thrown.
This would suggest that when done is called, you would need to call isCancelled to check if the worker was cancelled or not. If it was you would need to call destroy on the Process and shut down any secondary Threads you might have running.
You could use an additional SwingWorker to read the input from the process and utilise it's publish/process functionality to update the logs.
This would mean, you would start a SwingWorker to execute your external process. This would presumably be done in response to some event, like a button push.
When this worker's doInBackground method is called, it would execute the external process and call Process#waitFor. This would stop the doInBackground method from returning until the process has exited.
Before you call Process#waitFor, you could create another SwingWorker and pass the Process's OutputStream to it. This would allow this worker to process the output from the process independently. You would then be able to use this to send output of the process back to the EDT via the SwingWorker's publish/process functionality which could be added to something like a JTextArea.
This would save you a lot of hassle with dealing with SwingUtilities.invokeLater.
Do you need the second work? That depends on what you want to the workers to do. I tend to process all the output of external process in separate threads and allow who ever created the process to use waitFor, it isolates the responsibility a little more and prevents the IO from getting locked up an never reaching waitFor, but that's just me.
Take a look at Concurrency in Swing for more details
You can run bat file in java with Runtime
Runtime.getRuntime().exec("cmd /c start your_batch_file.bat");

Android Service Initialization. Should I use threads?

I'm coding a simple Android Service which will do some File IO intensive job.
The service will be running in the background for a while, and initializing the service will take a while. (It'll take longer as there are more files to scan).
So I thought that I should use a thread to initialize the service, since services are run on the UI thread. Will this be a good idea?
Should I wait for the initializing thread to end by calling the join() method and execute any more less time consuming jobs?
The reason I'm trying to use threads for initialization is because I don't want my activity starting the service to hang when my service is starting up.
Update
Okay, The reason I'm trying to use a service is to provide a means for an external client(such as a web browser, or a PC client) to access the files of my android phone. I also want to allow the service to keep running when my application goes to the background.
Do you really need a Service? If your code will do a lot of work in the Service it is always a good idea to do it in a thread. If you do not really need the Service, think of using an AsyncTask.
Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
http://developer.android.com/guide/components/services.html
Take a look at IntentService. It automatically runs in a separate thread and exits when it finishes its work. Seems like it would be appropriate for your situation.

When to use a thread / service in Android?

When should a thread or a service be used?
Should they be used for authentication? For instance, in my app I was considering using a thread or service (I am authenticating via Active Directory.)
Do you have examples of when each would be used?
Update: It seems the Android documentation includes a corresponding clarification now, see http://developer.android.com/reference/android/app/Service.html#WhatIsAService.
Original answer:
In Android, a Service does not provide any concurrent execution ("run in background"). It is actually more of a simple Java object which merely is instantiated (and managed) via the Android system instead of your application via new.
The most important property of a service is therefore not about deferring workload; this can be achieved with simple threads.
What makes a service object special is that it is registered with the Android system as a service. This let's the system know that this object provides some sort of service and should be kept alive as long as possible, or until it is stopped. Normal application threads do not have this special meaning to the Android system and will be terminated much more generously at the discretion of the system.
So, if you need some background activities to go on only while your application/Activity is active, a thread can do what you need.
If you need a component that keeps active will not be purged even when, after a while, the Android system decides to remove your Activities from memory, you should go for the service, or even a "foreground service", which is deemed even more important by the system and even less likely to be terminated to reclaim resources.
Of course, if desired, a Service object can also be made to contain one or more Thread instances which could then live as long as the Service object itself.
Edit:
Oh, plus: A service is, of course, the way to go if you want to provide some service(s) to other applications, which can "bind" to a service only.
A thread should be used in a long running process that would block the UI from updating. If it's more than a second or two you might want to put it into a background thread and notify the user with a dialog or spinner or something. If you lock the UI thread for more than 5 seconds the user will be prompted with a "kill or wait" option by the OS.
A service does not run on separate thread, so it will block the UI, but you can spawn a new thread within a service. A service is used more for something that should happen on an interval or keep running/checking for something when there is no UI shown.
Just look at this nice post Android Thread Constructs(Part 4): Comparisons
.
or Difference between Service, Async Task & Thread?.
Use service if you need something that is either used by other applications or outlives your application activities. The good example of service is file transfer that may take long time and you don't want to force user using your application during this time. Use thread (usually via AsyncTask or similar) in other cases.
For authentication purposes AsyncTask seems like a good choice.
I believe the main difference is about Android system attitude. Service is a part of android infrastructure, so android recognizes service as a working part of application and considers killing service as a last option. Moreover, you can tune up service priority in order to do it as important as foreground activity. As for threads, android does not recognize a thread as important part which must be kept. So usual threads has much more chances to be killed.
For instance If you have an activity which start a working thread and then go background, as android do not recognize thread as a working part, it may think that application do nothing, because no activity or service running and kill the whole app, including the working thread.
As per Android Developer Guide (http://developer.android.com/guide/components/services.html#Basics) :
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

Categories

Resources