Queuing threads in Android - android

my app wants to update pictures on the web on a regular basis. This doesn't require UI feedback, so I just start a new Thread and let it run. The problem is, that this update-method may be called before the previous one has been finished. How can I make sure that the second call doesn't start a new thread but is queued and automatically started when the previous one finished? Are handlers the right solution here as well?
Here the code:
public static void updatePictureOnPicasa(final PictureEntry pe) {
new Thread() {
public void run() {
try {
if(pe.isUpdated())
picasa.updatePicture(pe.getUrl(), pe.getDescription(), pe
.getTags());
} catch (Exception e) {
Log.e(Prototype.TAG, "Unable to update picture on Picasa "
+ pe.getUrl());
}
}
}.start();
}

You can use a service feature in Android.Please refer these links:
http://www.brighthub.com/mobile/google-android/articles/34861.aspx
http://marakana.com/forums/android/examples/60.html
Hope this will help you.

Related

How to automatically capture photos using an android app in every n seconds

I am trying to make an android app that captures photos after every 5 seconds. Currently the technique i'm using, uses the phone's camera app to capture the photo. It requires the user to capture the photo and then to press ok and only after that the control returns back to the android app. I found some codes to do the same without human interaction, but since i'm new to android, i'm not able to understand codes them because most of them are incomplete and divided into multiple activities. Can this be done using just one activity?
EDIT :
The codes mentioned above can be found here
I suggest to you to use this library (here documentation) instead the official Camera Api of Android that could be really tricky to use for beginners
Then your code could be like this
private final Handler handler = new Handler(); //This should be declared before OnCreate
private Runnable photoRunnable; //This also
CameraView camera = findViewById(R.id.camera);
camera.addCameraListener(new CameraListener() {
public void onPictureTaken(PictureResult result) {
//Handle result here!
}
});
photoRunnable = new Runnable() {
#Override
public void run() {
try {
camera.takePicture(); //The result will be in onPictureTaken
}
catch (Exception e) {
e.printStackTrace();
//Handle Exception!
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed(this, 10*1000); //10*1000 is your interval (in this case 10 seconds)
}
}
};
//runnable must be execute once
handler.post(photoRunnable);
Remember to manage the lifecycle of handler

How to run a code when all threads are done

I am new to threading and i went through many post in stack overflow and find many solution for my problem but i am not sure which one is best for which condition.
First thing first, my problem is that i want to update one JSON file
when all threads are done with the bitmap generation at a specific path so
that i can get that all those image and update JSON file. So in
simple word my i want to run some code when all thread are done with it
execution and major requirement is that i don't want my main to be blocked because of this.
What i have found out
thread. join
excutorServive
android-priority-jobQueue (link)
Mutex in threadpool ( also let me know if any other is there)
I am confused which one is the best way to tackle my problem. if any
android expert out there can summarise that for following the two
scenerio what is the best available in android.
wait till when all thread completes
don't wait and get informed when all completes
You can have counter for your threads, after each thread is complete check how many have already completed, if not all completed, increment the number of completed threads and the last thread to complete will then run the piece of code.
You can do it like this.
In your thread:
private Runnable runnableThread= new Runnable() {
#Override
public void run() {
try {
if (lastThreadDone){
handler.sendEmptyMessage("SUCCESS");
}
}
catch (Exception ex) {
throws ex;
}
}
};
lastThreadDone is boolean which will become true if the process is done, this is base on how you implement it.
then in you handler:
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
try {
switch (msg.what) {
case "SUCCESS": {
// your code here
break;
}
case "FAIL":
break;
default:
break;
}
}
catch (Exception ex) {
throw ex;
}
super.handleMessage(msg);
}
};
I would use a completion service and then poll until all tasks are finished. When they are done, the json file gets updated. The problem is that you need to do this async or you risk to block the ui. Therefore I would encapsulate the work with the completion service inside an intent service. If you need to update the ui you then can post local broadcasts from the intent service.
Furthermore for you cases
wait till when all thread completes
only do this when you are already on a background thread like intent service or async task
don't wait and get informed when all completes
implies the case above. Do the work async and notify the ui or some listening component with broadcasts, content observers, handlers or the 'onPostExecute' if you are using async task.

Why does runOnUiThread() not work inside Service?

I am creating an application that needs to update values every minute even if the app isn't running.
Of course, I have set up a simple Service to do that. I have debug messages set up to tell me when the Service starts, when it updates (every minute), and when it closes. I also have a message telling me when the values update inside a runOnUiThread() method. All of my messages activate except for the one in the runOnUiThread(). Is there something I'm doing wrong (of course there is)? What do I need to change?
Code:
#Override
public void handleMessage(Message message) {
try {
if (!serviceStarted) {
serviceStarted = true;
serviceTest = true;
while (serviceStarted) {
new MainActivity().runOnUiThread(new Runnable() {
public void run() {
OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");
}
});
Thread.sleep(((1 /* minutes */) * 60 * 1000));
System.out.println("Updated values through service.");
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
stopSelf(message.arg1);
}
So there's no need to do that, unless you're creating a Thread inside
of it
Gabe Sechan's answer is correct.
But if you are using a separate thread then instead of following code:
new MainActivity().runOnUiThread(new Runnable() {
public void run() {
OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");
}
});
Try, this code:
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");
}
});
As per Android docs
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).
You can't create an Activity by calling new. It doesn't initialize properly that way.
Also, Services by default run on the UI thread. So there's no need to do that, unless you're creating a Thread inside of it. If you are- runOnUIThread is just syntactic sugar for posting a runnable to a handler. So you can just do that instead.
Try using a handler or LocalBroadcastManager to send a message to the activity.
See this question: Accessing UI thread handler from a service
You can use Looper.getMainLooper() within a Handler to post a Runnable that executes whatever you're trying to execute.
A good alternative though, like jinghong mentioned, is to use broadcasts - in other words, use a different pattern.

What may prevent the UI in android to be updated on time?

I'm developing an Android app that has to update it's UI depending on receiving and processing some server responses, I'm using runOnUiThread for that. I have like five activities in that app, all is working very well but one requires me to relaunch the Activity(like going to another one and then returning to it) or interacting with it in order to that update takes place, and that is the way i'm using with all the Activities including the infected one:
runOnUiThread(new Runnable() {
public void run() {
try {
response_received(response);
} catch (Exception e) {
e.printStackTrace(); // never catch any Exceptions
}
}
});
private static void response_received(JSONObject response) throws Exception{
try {
int volume_setted = response.getInt(volume);
Normal_Activity.volume_value.setText(String.valueOf(volume_setted)); // the Volume TextView updated efficiently
Infected_Activity.volume_value.setText(String.valueOf(volume_setted)); // has the problem mentioned above
} catch (JSONException ex) {
}
}
I'm pretty sure the problem is not in the TextView as all the Activity UI has this problem but i just posted an example.
Do not directly set values in a Activity from another Activity. If you want to pass data to Another activity always use Intents. check the below link
pass data from intent to an other intent
If you want to start another activity and get result back check the below link
http://developer.android.com/training/basics/intents/result.html

how do you read text files off the internet in Android 4.0.3

I am a relatively new Android programmer and I was wondering how you could get read text off the internet in 4.0.3. I keep finding code that gives me a Network on Main exception: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html and was wondering if anyone could provide me some sample code to get around this, for reference I got the code I tried to use here: http://android-er.blogspot.com/2011/04/read-text-file-from-internet-using-java.html. Thanks a lot.
In Honeycomb and Ice Cream Sandwich (i.e. Android 3.0+) , you cannot connect to the internet in the main thread (onCreate(), onPause(), onResume() etc.), and you have to instead start a new thread. The reason why this has changed is because network operations can make the app wait for a long time, and if you're running them in the main thread, the whole application becomes unresponsive. If you try to connect from the main thread, Android will throw a NetworkOnMainThreadException.
To bypass this, you can run networking code from a new thread, and use runOnUiThread() to do things in the main thread, such as update the user interface. Generally, you can do something like:
class MyActivity extends Activity {
public onCreate(Bundle savedInstanceState) {
super.onCreate();
// Create thread
Thread networkThread = new Thread() {
#Override
public void run() {
try {
// this is where your networking code goes
// I'm declaring the variable final to be accessible from runOnUiThread
final String result = someFunctionThatUsesNetwork();
runOnUiThread(new Runnable() {
#Override
public void run() {
// this is where you can update your interface with your results
TextView myLabel = (TextView) findViewById(R.id.myLabel);
myLabel.setText(result);
}
}
} catch (IOException e) {
Log.e("App", "IOException thrown", e);
}
}
}
}
}
You need to complete an HTTP Request. There are a lot of examples available on line. Try here for starts.

Categories

Resources