im making an app that should send a message after certain amount of time via bluetooth.
The thread works fine when i use "Log" but when i use the write function of bluetooth, it seems to executes the loop when the app wants.
Hope somebody can help me:
public class AsyncWrite extends Thread {
#Override
public void run() {
while(true) {
try {this.sleep(250);} catch (Exception E) {}
//Log.e(TAG,"Test run");
mConnectedThread.write(A);
}
}
}
I've already try using asynctask executors and handlers, the result it's the same.
Related
I keep getting an illegal argument exception when running my app. However, this happens prior to the Toast messages coming up and that's why I think I need a delay.
Prior to adding on the DatabaseHelper class, my app was running and the proper value was coming up on both Toast messages, the one in the MainActivity and the one showing the intent value passed in the DisplayResult activity.
I'm not sure what to do at this point.
Just do a thread sleep in a runnable.
int timeYouWantToSleep = 60000;
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(timeYouWantToSleep);
//do your work here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
If this doesn't work, you know it's not a delay that you need.
What is happening in Android if I have IntentService defined as following:
public class BackgroundService extends IntentService {
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent workIntent) {
run();
}
private void run() {
try {
while(true)
{
//Some expensive Internet & SQL querying stuff
Thread.sleep(1000 * 60 * 60);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
How bad will it drain the battery?
I aim for rather fundamental answer (What will happen if I set the sleep to 1 day)?
You question to so close to this one. He also trying to do some work inside a loop and make the Thread sleep.
From the Geeks answer in the provided question, I can tell you that it depends on the //Some code line and what will you replace it with. You might replace it with an intensive code that use the internet, GPS, Flash, Camera and consume your battery for sure OR you might replace it with nothing and let the Thread sleep which allow the CPU to replace it with any other Thread that needs to perform anything.
I must use Thread in an Android project. Sometimes, it works corectly, however sometimes does not; it does not start (does not call SendToServer() method)or it starts but return to another function suddenly (return updated; line)before the thread does not finish.
Note: affected value is bigger than 0, it gives condition and it goes to if statement.
Here is the my code sample;
public static Boolean MyUpdateFunction(MyObject myobject){
Boolean updated=false;
//Code for updating local database
int affected= SqliteDb.update(....);
if(affected>0)
{
//Send updated data to server
//For this I must use Thread(I can't use AsyncThread)
updated=true;
SendToServer();
}
return updated;
}
public static void SendToServer()
{
try{
;
Thread th=new Thread(new Runnable() {
public void run() {
try {
//Create data and send it to server
//.......
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
th.start();
th.join();
}
catch(SQLException e)
{
Toast.makeText(myContext,"ERROR: "+e.getMessage(), Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Other people are correct in that an AsyncTask is the way forward, but the direct problem due to what you're experiencing is this (and as such, I would recommend reading up on how Threading works):
When you start the thread, it begins a new process. The UI thread (which is generally where the majority of your code is) continues. So your code will fire the thread with SendToServer(), and then by definition will immediately return updated, as the UI thread immediately goes to the next line.
What you need is a callback from your Thread, which is handled in the onPostExecute() method of an AsyncTask. There's a good tutorial on how to use them and what they do here
Edit:
I've just seen from a comment above that you can't use Asynctasks, fair enough, but you still need a callback/event fired from your Thread to return any results
Instead of using threads and your variables (updated and affected), you can use AsyncTasks: see: http://developer.android.com/reference/android/os/AsyncTask.html
With AsyncTask, you have some methods which are doing exactly what you want:
onPreExecute
doInBackground
onPostExecute
So, what you can do is to check your condition in onPreExecute, then do your SendToServer in the doInBackground and onPostExecute do what you need.
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.
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.