Android: how run simple background loop - android

Hej, I'm trying to create an app that runs on a main thread, but also has a background loop running (to check for a connection).
I just want to call a certain function onCreate, and that function should run in the background...I've tried with the code below, but doesn't seem to work...any suggestions?
void doStuffBackground()
{
Thread testingForBluetooth = new Thread()
{
public void run()
{
try
{
for(int i = 0; i < 100; i++)
{
writeTerminal('x');
sleep(100);
}
}
catch(Exception e)
{
Log.e("Threading", e.toString());
}
finally
{
finish();
}
}
};
}
}
But again...not working?
Thanx in advance

You never started the thread.
Anyway if you need a background task, you could also try a service.

Related

Android runOnUiThread not executing

I have this problem. I'm trying to update my TextView from another thread and it's not letting me.
I have tried a bunch of different solutions and none of those didn't seem to help. In my while loop code is printing that "Started new loop" all the time but it's not continuing from that runOnUiThread.
Can anyone help me figure out how to update TextView from another thread?
//second thread
protected void startKakkosThread() {
Thread t2 = new Thread() {
public void run() {
while (true) {
System.out.println("Started new loop");
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if(rullaavaNumero >= 0) {
rullaavaNumero--;
System.out.println(rullaavaNumero);
pelaajanPisteetTeksi.setText("" + rullaavaNumero);
sleep(1000);
}else{
rullaavaNumero = 9;
System.out.println(rullaavaNumero);
pelaajanPisteetTeksi.setText("" + rullaavaNumero);
sleep(1000);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
});
}
}
};
t2.start();
}
Here is a quick fix, you have an infinite loop that runs faster than a thread can have a chance (time) to start. So even thus you have a sleep in side your thread with if statement, if the thread never starts then sleep have no effect.
And your sleep inside a Thread won't work like this. You want to delay your infinite while loop, therefore you need to move sleep on out of the thread in your while loop.
It is still possible to delay your thread by adding extra sleep in it, but all that depends on what you want to achieve.
Your final code would look like this:
protected void startKakkosThread() {
Thread t2 = new Thread() {
public void run() {
while (true) {
System.out.println("Started new loop");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (rullaavaNumero >= 0) {
rullaavaNumero--;
System.out.println(rullaavaNumero);
pelaajanPisteetTeksi.setText("" + rullaavaNumero);
// no need for sleep here
// sleep(1000);
} else {
rullaavaNumero = 9;
System.out.println(rullaavaNumero);
pelaajanPisteetTeksi.setText("" + rullaavaNumero);
// no need for sleep here
// sleep(1000);
}
}
});
// add this part
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t2.start();
}
I have test it and it works, you could also go what #cricket has suggest.
My eye saw another issue, which is not a part of your question, but good to mention. I assume you want to count from 9 to 0, if that is the case, you need to correct following line by removing = otherwise you get counts till -1, so your code line would look like this:
if(rullaavaNumero > 0) {...

Android Input Method suggestion asynchronously from web service

I wants to create a custome Input Method with word suggestions from a webservice in an asynchronous way. If it is not asysnchronouse , phone get stuck while connecting to internet. If I use Thread it cause an excpetion "ui can be touch only by the tread created ". I don't know runOnUIthread can be used or how. I understood that runOnUiThread activity method. Anybody please help. I used android Example app softkeybord.
I'm not sure I understand,
If the definition of the Thread is inside the Activity,
You can just call:
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();

how to stop a running thread with button toggle (android app)

I finally got my app working, i just have one issue which i would like to correct.
I have a button which controls a thread that runs a couple function in the background. The functions in the background eventually stop the thread whenever a certain value is reached. What i am having issues doing is pressing that same button again to just stop the thread manually. Currently I can only start the thread and wait for itself to finish. I am able to do other things in the app, so the thread is running on its own, i just want to kill it manually.
public void onMonitorClick(final View view){
if (isBLEEnabled()) {
if (!isDeviceConnected()) {
// do nothing
} else if (monitorvis == 0) {
showMonitor();
DebugLogger.v(TAG, "show monitor");
//monitorStop = 4;
Kill.runThread(); // I want a function here that would kill the
// thread below, or is there something that
// can be modified in runThread()?
// I did try Thread.Iteruppted() without luck
shutdownExecutor();
} else if (monitorvis == 1) {
hideMonitor();
DebugLogger.v(TAG, "hide monitor");
monitorStop = 0;
runThread(); //The running thread that works great on its own
}
}
else {
showBLEDialog();
}
}
private void runThread() {
new Thread() {
int i;
public void run() {
while (monitorStop != 3) { //This is where the thread stops itself
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
((ProximityService.ProximityBinder) getService()).getRssi();
rssilevel = ((ProximityService.ProximityBinder) getService()).getRssiValue();
mRSSI.setText(String.valueOf(rssilevel) + "dB");
detectRange(rssilevel);
}
});
Thread.sleep(750);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
On first look, you could simply set monitorStop = 3, which would cause the thread to eventually stop after it's timeout completes.
The problem with this, is that I presume if you push the button again or your code modifies monitorStop at some point in the future, then the thead you wanted dead, might stay alive. ie: monitorStop will need to stay equal to three for at least 750ms to assure the thread will comlete it's loop and die.
The correct way to do this would be to create your thread as a new class with it's own monitorStop parameter. When you create the thread, you would keep a reference to it and modify the thread's monitorStop parameter. This way the thread would finish without interruption. If you wanted to create a new thread, then this would not affect the old thread from finishing appropriately.

Add a runnable thread inside an Async Task for splash screen delay

Hi I wanted to add a delay on my splash screen using a Async Task but I can't figure out how should I do it. Here's my DoInBackground code so far:
#Override
protected Integer doInBackground(String... params) {
Thread SplashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while(running && (waited < delayTime)) {
sleep(100);
if(running) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
stop();
}
}
};
SplashThread.start();
return null;
}
I think the part of the return null is the main cause of problem since it's ending up my Async Task even my SplashThread is still running in background leaving a leak on thins part onwards which lead to error. I also tried to use counDownTimer as a subtitute but this leads in the same problem. Any ways to do this properly?
You don't need the additional thread that you start in the doInBackground method of your AsyncTask. The AsyncTask itself runs the doInBackground method in another thread, also,
because of this the while loop it's most likely unnecessary. Do the work you want to do in the doInBackground method and then simply return. If you want/need some additional delay(although you should avoid this at all costs) you can use the Thread.sleep method to pause the thread before returning.

progress related problem in android using Threading!

friends,
i am using following code to display progress on andorid activity when i call web service method to getposts it show progress. but when call of serivce is complete my application gets crashed.
please guide what mistake am i doing or any other alternative way to achieve this goal?
mProgressStatus = 0;
Thread th=new Thread(new Runnable() {
public void run() {
if (mProgressStatus < 100) {
myProgressBar.setVisibility(View.VISIBLE);
} else {
myProgressBar.setVisibility(View.GONE);
}
}
});
th.start();
results = p.GetPosts(p, PageSize, adap.getCount());
mProgressStatus=100;
th.stop();
So, if your application crashes, maybe you should look at the error message first? Or at least provide it for us.
(A tip: I read three posts of you today and you always have trouble with the first/last lines of your code pasting, please check you code pasting before you submit a question...)
You can try using runOnUiThread, if you are in an activity class
mProgressStatus = 0;
MyActivity.this.runOnUiThread(new Runnable() {});
public void run() {
if (mProgressStatus < 100) {
myProgressBar.setVisibility(View.VISIBLE);
} else {
myProgressBar.setVisibility(View.GONE);
}
}
});
Everything about the UI have to be executed in the UI Thread

Categories

Resources