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);
}
}
Related
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
}
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;
}
}
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!
I have a service which contains a Timer and TimerTask for receiving data from Webservice in periods of time. When my TimerTask runs, the UI hangs until the Webservice process complete. How can I put my task in a thread to prevent the UI hanging?
My code:
Timer timerSyncFull = new Timer();
class taskSyncFull extends TimerTask {
#Override
public void run() {
hSyncFull.sendEmptyMessage(0);
}
};
final Handler hSyncFull = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
procSyncFull();
return false;
}
});
public void procSyncFull() {
try {
// My webservice process
} catch (Exception e) {
}
}
#Override
public void onStart(Intent intent, int startId) {
timerSyncFull = new Timer();
timerSyncFull.schedule(new taskSyncFull(), 5*60*1000,
5*60*1000);
}
Use AsyncTasks or attach your Handler to another Looper thread.
I used the following code and my problem solved:
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 {
showToast("some text");
//My Main 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();
}
}
final Handler hToast = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Toast.makeText(SrvDataExchange.this,
msg.getData().getString("msg"),
Toast.LENGTH_LONG).show();
return false;
}
});
private void showToast(String strMessage) {
Message msg = new Message();
Bundle b = new Bundle();
b.putString("msg", strMessage);
msg.setData(b);
hToast.sendMessage(msg);
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
Simply invoke your procSyncFull() method in thread or asyncTask.
final Handler hSyncFull = new Handler(new Callback() {
#Override
public boolean handleMessage(Message msg) {
Thread thread=new Thread()
{
public void run(){
procSyncFull();
}
}
return false;
}
});
private Handler webserviceCompletionHandler=new Handler()
{
#Override
public boolean handleMessage(Message msg) {
return false;
}
};
use AsyncTask carry out your execution in doInBackground() and populate it in onPostExecute()
AsyncTask Example
Implementing a Thread by providing a new class that extends Thread and overriding its run() method is new to me. I've tried all day to get it to work. Here's my code:
/*
* see http://developer.android.com/reference/java/lang/Thread.html
*/
class threadClass extends Thread {
private Handler mHandler;
private Message mMsg;
// constructor
public threadClass(Handler handler, Message msg) {
// do something like save the Handler reference
mHandler = handler;
mMsg = msg;
}
#Override
public void run() {
// do some background processing, call the Handler?
mHandler.sendMessage(mMsg);
}
}
public Thread passHandlerToThread(Handler handler) {
handler.sendEmptyMessage(10);
Message msg = Message.obtain();
msg.what = 10;
Thread thread = new threadClass(handler, msg);
return thread;
}
private Handler localHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
int what = msg.what;
if (what == 10) Log.i("localHandler", "what: " + what);
}
};
public void startThread() {
Thread thread = passHandlerToThread(localHandler);
thread.start();
}
I call startThread() in my LocalService onCreate() but nothing happens. What am I doing wrong? I was expecting localHandler() to be called twice: once in passHandlerToThread() and again in run().
Do something like this:
private final Handler handler = new Handler();
// toast runnables
final Runnable updateTwitterNotification = new Runnable() {
#Override
public void run() {
dismissProgressSpinner();
Toast.makeText(getBaseContext(), "Tweet sent!", Toast.LENGTH_LONG).show();
}
};
final Runnable updateCreateError = new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Tweet error!", Toast.LENGTH_LONG).show();
}
};
postMessageInThread();
//implementation:
private void postMessageInThread() {
Thread t = new Thread() {
#Override
public void run() {
try {
connectToTwitterService() // or whatever
handler.post(updateTwitterNotification);
} catch (Exception ex) {
Log.e(TAG, "Error sending msg", ex);
handler.post(updateCreateError);
}
}
};
t.start();
}