control android refresh time according to webpage output - android

If i have something like example.com/time.php and the output is just 20000 so How can i link this to control time of refresh, Any Idea?
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(10000); // here is the number which should be linked to the webpage output
runOnUiThread(new Runnable() {
#Override
public void run() {
// update View here!
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();

You should use handler for easier implementation.
Handler handler = new Handler();
Runnable test = new Runnable() {
#Override
public void run() {
//do work
handler.post(test, 4000); //wait 4 sec and run again, you can change it programmatically
}
};
public void stopTest() {
handler.removeCallbacks(test);
}
public void startTest() {
handler.post(test,0); //wait 0 ms and run
}

Related

Changing image src over time

Im pretty new to android and I'm trying to make an imagebutton in android studio that changes images at set inervals. I tried to just use wait and put it into a different thread but that doesn't seem to work. All I want if for the image to change while also still allowing for a mp3 to be played whilst doing so.
Runnable r = new Runnable() {
#Override
public void run()
{
synchronized (this)
{
try
{
wait(1000);
ank.setImageResource(R.drawable.shank2);
wait(1000);
ank.setImageResource(R.drawable.shank3);
wait(1000);
ank.setImageResource(R.drawable.shank4);
wait(1000);
ank.setImageResource(R.drawable.shank5);
}
catch (Exception e) {}
}
}
};
Thread myThread = new Thread(r);
myThread.start();
Simple way:
public void changeImages() {
Handler uiHandler = new Handler();
uiHandler.postDelayed(new Runnable {
#Override
public void run() {
ank.setImageResource(R.drawable.shank1);
}
}, 1000);
uiHandler.postDelayed(new Runnable {
#Override
public void run() {
ank.setImageResource(R.drawable.shank2);
}
}, 2000);
...
}
Better way:
public void changeImages() {
int[] images = new int[] { R.drawable.shank1, R.drawable.shank2 ... }
long delay = 1000;
Handler uiHandler = new Handler();
for (int imageRes : images) {
uiHandler.postDelayed(new Runnable {
#Override
public void run() {
ank.setImageResource(imageRes);
}
}, delay);
delay += 1000;
}
}
The best way
final Handler uiHandler = new Handler();
final Queue<Integer> queue = new LinkedBlockingQueue<>();
void changeImages() {
queue.add(R.drawable.shank1);
queue.add(R.drawable.shank2);
...
loopImages();
}
void loopImages() {
if (!queue.isEmpty()) {
uiHandler.postDelayed(new Runnable() {
#Override
public void run() {
ank.setImageResource(queue.poll());
}
}, 1000);
}
}

how can I write the code inside Application class to get Toast message every 5 seconds from the background

I am new to android and I want to get a Toast message from the background every 5 seconds but my app becomes not responding. I spent all the day to solve this problem :( but I can't
Can anyone help me?
thanks,
here is my code:
public void onCreate() {
super.onCreate();
System.out.println("Application Created");
new Thread(new Runnable() {
#Override
public void run() {
service1();
while (true) {
try {
Thread.sleep(5000);
mHandler.post(new Runnable() {
#Override
public void run() {
// here to update the UI
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
private void service1() {
Toast.makeText(appApplication.this, "Service 1", Toast.LENGTH_LONG).show();
}
You need to use runOnUiThread() when you want to update your UI from a Non-UI Thread, something like this:
private void showMessage() {
new Thread() {
public void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Service 1", Toast.LENGTH_LONG).show();
}
});
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
Or you can use Timer with TimerTask and Handler:
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
// Call this to start showing the message.
private void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
timerTask = new TimerTask() {
public void run() {
//use a handler to run process
handler.post(new Runnable() {
public void run() {
/**************************/
/** Do your process here **/
/**************************/
Toast.makeText(getApplicationContext(), "Service 1", Toast.LENGTH_LONG).show();
}
});
}
};
//schedule the timer, start run TimerTask then run every 5000ms i.e 5 seconds.
timer.schedule(timerTask, 0, 5000);
}
// Call this to stop the timer.
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}

Toast every X seconds

I have a function that gets executed every 0.~2 seconds (due to lag). However, I would like to perform a toast every 5 seconds. May i know how I can achieve this ?
public void navigation(Coordinate userPosition , Coordinate destination){
if (Math.abs(userPosition.y - destination.y) > 500) {
{Toast.makeText(this, "Walk for " + Math.abs(CheckPoint.y - UserPosition.y) + "mm", Toast.LENGTH_SHORT).show(); }
}
Above is a sample of my current code. The frequency of which the toast gets executed is dependent on the current 'lag'. I would like the toast to be sent every 5 seconds minimum.
You can do it this way:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
navigation(...);
handler.postDelayed(this, 5000);
}
}, 5000);
try this for exactly five second,
int count = 100; //Declare as inatance variable
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final Toast toast = Toast.makeText(
getApplicationContext(), --count + "",
Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 5000);
}
});
}
}, 0, 5000);
Create a Thread and loop that thread
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread = new Thread( runnable );
myThread.start();
class CountDownRunner implements Runnable
{
// #Override
public void run()
{
while( !Thread.currentThread().isInterrupted() )
{
try
{
navigation(); // do the work here
Thread.sleep( 2000 ); // time interval for the counter. it will run every 2 sec
}
catch( InterruptedException e )
{
Thread.currentThread().interrupt();
}
catch( Exception e )
{
}
}
}
}
public void navigation(Coordinate userPosition , Coordinate destination){
if (Math.abs(userPosition.y - destination.y) > 500) {
{Toast.makeText(this, "Walk for " + Math.abs(CheckPoint.y - UserPosition.y) + "mm", Toast.LENGTH_SHORT).show(); }
}
Maybe with a loop Thread? Try it out:
private Thread loopThread = new Thread(new Runnable() {
public void run() {
while(true){
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(this, "Your text!", Toast.LENGTH_SHORT).show();
});
Thread.Sleep(5000); //Wait 5 seconds, then repeat!
}catch (Exception e) {
return;
}catch (InterruptedException i) {
return;
}
}
}
});
Then start the Thread wherever you want like:
Thread myThread = new Thread(loopThread);
myThread.start();
And stop it with:
myThread.interrupt();
Hope it helps!

Getting error while implementing thread android

Am new in android .. am trying to implement thread in a android. But am getting error .. I googled and getting answer "AsyncTask", but truly i dont know how to implement
Error message
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
my code
final Thread thread = new Thread(){
#Override
public void run() {
try {
DatabaseHandler dbh = new DatabaseHandler(test.this);
result=dbh.Verify(1);
if(result != ""){
getData();
progress.dismiss();
}
else{
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
Use following code to run in UI thread.
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.post(new Runnable() { // This thread runs in the UI
#Override
public void run() {
DatabaseHandler dbh = new DatabaseHandler(test.this);
result=dbh.Verify(1);
if(result != ""){
getData();
progress.dismiss();
}
else{
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
new Thread(runnable).start();
Seems like you need to create your handler in MainActivity and then pass it further. Like so:
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
}

How can I put Toast in a Runnable of a Service?

I have a service which contains a Timer and TimerTask for receiving data from Webservice in periods of time. everything works fine except Toast. I want to show a Toast to user in procSendMapMovements but i get exception. How can I use Toast in it?
class taskSendMapMovements extends TimerTask {
#Override
public void run() {
hhSendMapMovements.sendEmptyMessage(0);
}
};
// /////////////////////
final Runnable rSendMapMovements = new Runnable()
{
public void run()
{
procSendMapMovements();
}
};
final Handler hhSendMapMovements = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
performOnBackgroundThread(rSendMapMovements);
return false;
}
});
// /////////////////////
public void procSendMapMovements() {
try {
Toast.makeText(SrvDataExchange.this,
"some texts"
Toast.LENGTH_SHORT).show();
// exception here
// my process
} catch (Exception e) {
}
}
#Override
public void onStart(Intent intent, int startId) {
try {
timerSendMapMovements = new Timer();
timerSendMapMovements
.schedule(new taskSendMapMovements(),
10*60*1000,
10*60*1000);
//
} catch (NumberFormatException e) {
Toast.makeText(this, "error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "error running service: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
Create a handler to display toast.
Use following:
where you want to display toast call:
//printToast.sendEmptyMessage();//If you dont want to send no paramter
//if you want to send some object to handler
/*
Message msg=printToast.obtainMessage();
msg.obj=objToSent;
printToast.sendMessage(msg);
*/
final Handler printToast= new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Toast.makeText....;
}
});
**
Handler printToast= new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Toast.makeText....;
}
});
your Runnable
{
run()
{
do what ever you want
printToast.sendMessage(printToast.obtainMessage());
}
}
**

Categories

Resources