I am making a client socket program in Android, it sends and receive data correctly, but my problem is the client is running in the "doInBackground" of the Asyntask. I need the info the client receives from the server in order to continue with rest the processes, and there is my question and the approach I need, how I make the program wait until the client socket method receives the data before calling the others methods?
Example :
1)
MyClientTask myClientTask = new MyClientTask(server, port);
myClientTask.execute();
2) Do_something_with _data_received();
3) Do_something_else_with _data_received();
The point 2 will run with the client socket at the same time in this approach.
Thanks in advance.
If you are working with a fragment pass the fragment to the asynctask.
Do the logic in doInBackground() then fragment.method() in onPostExecute().
onPreexecute and onPostExecute run on the UI thread, doInBackground() runs on a separate thread.
Hint: you could replace the view with a progress(circular) untill asynctask is done,
onPostExecute(){
if(fragment.isAdded()){
fragment.drawUI();
}
}
where the drawUI() is the logic that makes your layoutView and makes it visible.
onPostExecute(){
2) Do_something_with _data_received();
3) Do_something_else_with _data_received();
}
TIP : Don't call .get() of asynctask because it will freeze UI thread.
Related
I am using priority job queue , there are number of jobs running in parallel, so that their result populates on UI at same time which takes application to ANR, is there any way , so that i can run asynchronous calls and populate ui synchronously?
UI is always populated synchronously, if it is done in correct way. The correct way is to call activity.runOnUiThread(Runnable), directly or indirectly. Seems that your problem is that your jobs post to UI thread in a too high rate.
First, check if the Runnables to update UI does only UI work. Any calculations should be done outside the UI thread. If it is so, create an intermediate object which makes pauses between UI updates from the parallel jobs and so lets the UI thread to respond to updates from user. It can look as follows:
public class PauseMaker {
Semaphore sem = new Semaphore(1);
public void runOnUiThread(Runnable r) {
sem.aquire();
Thread.sleep(1);
activity.runOnUiThread(new Runnable(){
try {
r();
} finally {
sem.release();
}
});
}
}
You can use the zip operator of rxjava2 to merge the responses together and when the combined response comes you can populate the UI synchronously .. for reference you can check..
http://www.codexpedia.com/android/rxjava-2-zip-operator-example-in-android/
Note The zipper will the return merged response after all the responses are received
I also faced with the NetworkOnMainThreadException in my application but I don't see how to resolve it.
I have a class with a getter method. Like:
public ArrayList<News> get(int i){
// get the list of news from a HTML on the net. The news are split up into web pages on the site
// and i is the page number
return NewsParser(i);
}
Since Android throws the exception I come up with an idea of a downloader class which downloads the HTML content in a separate thread
pubic ArrayList<News> get(int i){
Downloader dl = new Downloader(i);
String HTMLcontent = dl.getContent(); <-- AsyncTask starts in getContent()
return NewsParser(HTMLcontent); <-- What happens here in the main thread???
}
Any ideas/best practices for this problem?
Just looking at your code and your question, it seems like you don't have a very solid understanding of how AsyncTask (or threads in general) works.
I would recommend reading this article.
Basically, your AsyncTask should query the web URL and download the data. Once the data is complete, your AsyncTask should send the HTMLContent to a handler object. The handler will be running on your main thread, so you can display the information to the user at that point.
You shouldn't be calling
dl.getContent();
to retrieve the content. AsyncTask runs on a separate thread, so you can't just call methods like this from your main thread. You need to create the Downloader object (like you did) and then call
dl.execute();
to start the AsyncTask.
run the get method inside a thread,
new Thread(new Runnable() {
#Override
public void run() {
// call get method here
}
}).start();
Since Honeycomb (Android 3.0) you can't use Networking Operations in the MainThread to avoid freezes on the Phone. This is important in order to make your app responsive.
More info:
NetworkOnMainThreadException
Responsiveness
I have an app, which uses several HTTPRequests for example
get a session id
get some locationdata
get existing categories
(...) and some more
I created a HTTPRequestHandler, which basically manages all the AsynTasks for each Request... This works well, but my problem is, I don't know a good way for managing the different AsynTasks. For example, you need to get the SessionId Task before you can start the GetSomeLocationData Task
So in my HTTPRequestHandler I have a queue, which starts the depending AsyncTasks like:
private void startSessionIdTask(...) {
//...
GetSessionIdTask mGetSessionIdTask = new GetSessionIdTask(this);
mGetSessionIdTask.execute(url);
}
//and from the postExecute() in GetSessionIdTask I call
public void setSessionId(int mSessionId) {
mDataHelper.setmSessionId(mSessionId); //set id
String url = API_URL + API_GET_FAVORITES + URL_VARIABLE;
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("session_id", getSessionId()));
String paramString = URLEncodedUtils.format(params, "utf-8");
url += paramString;
//and finally start another Tasks (and so one...)
GetLocationsTask mGetLocationsTask = new GetLocationsTask(this);
mGetSessionIdTask.execute(url);
}
However, this works fine, but the problem is, that (depending on the connection), this queue takes time, and the user can start other AsynTasks which fail, because some initially data is not loaded yet.
I could set some Boolean like isSessionIdLoaded or could block the UI for the user, but I'm wondering, if there s any better solution?!
So my question is: Is there a way to put asyntasks in some kind of queue (ArrayList, Map..) which will be executed in a row?
As of Android 3+ AsyncTasks will be executed in serial on the AsyncTask.SERIAL_EXECUTOR. So by default if you start 2 AsyncTasks
task1.execute();
task2.execute();
Task2 will only be executed if task1 has finished (just check the sdk implementaion of AsyncTask.SERIAL_EXECUTOR). This can be pushed to that point, that if task1 for any reason never finishes, task2 will never start and you have deadlocked your app.
If you want your own queue independed from the default SERIAL_EXECUTOR, just use
public final AsyncTask<Params, Progress, Result> executeOnExecutor (Executor exec, Params... params)
And provide your own executor (aka threadpool). For one project I copyed the SERIAL_EXECUTOR implementation to have 2 serial queues.
For Android 2.3 to 1.6 all tasks are by default in parallel, similiar to calling in Android 3+:
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,null);
Unfortunatly in Android 2.3 und lower you have no option of specifing the executor on which the task/thread will be run on. So if you want to have it done serially, you have to implement it yourself, by calling task2 only after task1 has finished explicitly in onPostExecute(). This concept can of course be pushed to use a queue of task where the former task will call the next one when it's finished (= serial worker queue). For this you will find plenty literature and patterns.
I'm not entirely sure what you're asking, but if you'd just like a way to queue up Runnables to execute in a background thread in sequence, then Executors.newSingleThreadExecutor() may be what you're looking for. It's more complicated than it probably needs to be, but you can find examples and tutorials easily enough via google.
If you need sequential execution, I'd recommend switching to IntentService instead of using AsyncTask. See docs: http://developer.android.com/reference/android/app/IntentService.html
I've been reading up on how to use Thread in java, and I'm hoping someone can help me verify I'm using it correctly. I'm concerned that I should be calling .interrupt() or destroying the thread in some way.
I have a simple script that just hits my server to verify some data. My code:
Thread checkregister = new Thread(){
#Override
public void run(){
checkSystem();
}
};
checkregister.start();
Where checkSystem() posts the device id to a php script and waits for the response via HttpClient & HttpResponse. There isn't any looping so I don't think blocking is called for, but please let me know if I'm wrong.
No need to destroy the Thread. The Thread is effectively taken out of the thread scheduler as soon as run() returns.
If for some reason you need a way to prematurely "end" the Thread, this is a bit more complicated and there's been a lot of discussion about the proper way to do it. Simple way though is to just call stop() on the Thread.
I have a client software (on Android) that listens to incoming messages. The messages are received in a while loop that waits for messages to come. When a message is found, it updates the GUI. [Since in Android, GUI can not be updated directly ] A thread is called to do this. My problem is, if there are many messages, results in many threads! And it creates a clumsy situation. My abstract code is,
My_Client()
{
send_text_function() // My question is not about it
in_a_thread_Call_receive_from_others_function() [see 1]
}
receiving_funtion() // [this function is mentioned above as (see 1), called in a thread]
{
while( waiting for new message)
{
>>A new message found >> create a thread to update the GUI. // << Here is my question. see 2
//android.os.Handler.thread type thread!
}
}
label 2: Now this thread is created each time there is a message. How can I just create one thread and keep using it again and again? Any idea?
Create a new Thread.
In the run() method of the Thread create a new Handler.
When you want to do something on the target thread, use the Handler's post() method.
You can create a Handler on the Main thread to post-back operations that update the GUI.
Also consider using AsyncTask<>.