I am trying to create one application which checks battery status every one minute and update the UI with the battery Level.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
batteryPercent = (TextView) this.findViewById(R.id.battery);
while (true) {
runOnUiThread(mRunnable);
}
}
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
getBatteryPercentage();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
`getBatteryPercentage()1 update a text view on UI.
When I call getBatteryPercentage() only once the code works fine, but when I try to run it in a loop like above, after few seconds I get Application Not Responding(ANR).
Is there any way to make the app wait for 60 seconds without getting ANR?
Don't do it with Sleep. Use a CountDownTimer instead.
CountDownTimer _timer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
batteryPercent = (TextView) this.findViewById(R.id.battery);
_timer = new CountDownTimer(Long.MAX_VALUE, 60000) {
#Override
public void onTick(long millisUntilFinished)
{
getBatteryPercentage();
}
#Override public void onFinish() {}
};
_timer.start();
Don't forget to call _timer.cancel() before the Activity exits.
You can use Handler.postDelayed for this.
Handler handler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
getBatteryPercentage();
handler.postDelayed(mRunnable, 60000);
}
}
And then:
handler.postDelayed(mRunnable, 60000);
if you do something in android uithread more than 5 seconds,the application will show ANR toast.
you should do while loop in another thread,and use callback to refresh ui.you can do it like this:
new Thread(new Runnable(){
public void run(){
try{
Thread().sleep(6*1000);
updateUI();
}catch( Exception e){
e.print***();
}}}).start();
private void updateUI(){
runOnUiThread(new Runnable(){
getBatteryPercentage();
});
}
Related
I try to implement a thread that runs next to the main thread, this thread isexecuted in 20 seconds, I need that after finishing the thread again it executes again in a continuous way.
With this code the thread is executed once, but how do I do it to run again?
public class MainActivity extends AppCompatActivity {
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
.
.
treadTimer();
}
private void treadTimer(){
new Thread(new Runnable() {
#Override
public void run() {
for(int i=1; i<= 20; i++){
UnSegundo();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Tarea Larga Finalizada", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
private void UnSegundo(){
try{
Thread.sleep(1000);
}catch (InterruptedException e){}
}
}
This is one of the ways
Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#override
public void run() {
doYourThing();
handler.post(this, 20000);
}
}
handler.post(runnable);
this is a simple code to understand the runnable .I tried but not working . can you guys help me pls this is my code
public class Autostart extends activity implements Runnable {
#override
public void run (){
System.out.println ("message");
}
}
}
this not printing any statements
If you are using an Activity, you need to write your code inside Activity lifecycle methods. onCreate() is called when the Activity is created. So starting your Runnable here would be the correct way to do it.
#Override
public void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
System.out.println ("message");
}
};
handler.postDelayed(r, 1000);
}
You have to create a Thread object and call start() using that object.
Thread t = new Thread(this);
t.start();
Or Just use Handler
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do Something here
}
}, 5000);
You can use below code to print a value after regular interval of time
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("on print timee", your value);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // will execute after 1 sec
}
Hope this will help you
I found a similar solution to Swayam (android implements runnable not working?), however another handler.postDelayed reference within run() was required;
public void onCreate(
...
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
Log.i(TAG, "message");
handler.postDelayed(this, 1000);
...
}
};
handler.postDelayed(r, 1000);
Try following code
Handler mainThreadhandler = new Handler(getMainLooper());
mainThreadhandler.post(new Runnable(){
public void run(){
// UI work
}
});
public class Autostart extends activity implements Runnable {
Thread = thread;
#override
public void onCreate() {
thread = new Thread(this);
thread.start();
}
#override
public void run (){
System.out.println ("message");
}
}
Hi guys i have a Thread into a Activity.
I want know the status of the thread when i run the Activity...
Is possible know the status of thread?
Example:
if thread not running, start now.
Whenever i run the Activity, the thread start :(
Thread:
public void callAsynchronousTask(Timer timer, final ToggleButton btnAtterraDecolla,
final ToggleButton btnRitardo, final ToggleButton btnImbarco)
{
final Handler handler = new Handler();
isTimerRunning = true;
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
tTask aTask = new tTask(); //THIS IS ASYNCTASK
if(btnAtterraDecolla.isChecked())
LOL(1,AoP,btnAtterraDecolla);
if(btnRitardo.isChecked())
LOL(2,AoP,btnRitardo);
if(btnImbarco.isChecked())
LOL(3,AoP,btnImbarco);
aTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, TEMPO_ESECUZIONE_THREAD); /
}
In onDestroy()
#Override
public void onDestroy() {
stopUpdates(btnAtterraDecolla,btnRitardo,btnImbarco);
super.onDestroy();
}
private void stopUpdates(ToggleButton btnAtterraDecolla,ToggleButton btnRitardo,ToggleButton btnImbarco) {
if(!btnAtterraDecolla.isChecked() && !btnRitardo.isChecked() && !btnImbarco.isChecked()){
if (isTimerRunning) {
timer.cancel();
timer.purge();
timer = null;
isTimerRunning = false;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....callAsynchronousTask(...)
And here i want stop the thread ONLY IF btn1,btn2,btn3 is NOT checked!
There is a solution for this problem?
Thank you in advance!
There are some way can check the Thread properties
You able to check Thread is Alive() by
Thread.isAlive() ,
method it return boolean.
You able to found running thread run by
Thread.currentThread().getName()
I want to change the image in imageView after 5 seconds from app start.
This is the code that I tried so far:
public class MainActivity extends Activity {
ImageView screen;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen=(ImageView)findViewById(R.id.imageView1);
screen.setImageResource(R.drawable.ic_launcher);
}
}
You can use a Handler, such as:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// change image
}
}, 5000); // 5000ms delay
As Sam says in the comments, you could also do this (because all Views have their own handler):
screen.postDelayed(new Runnable() {
#Override
public void run() {
// change image
}
}, 5000); // 5000ms delay
See the Handler Documentation.
you can try thread like this:
new Thread(){
public void run(){
//sleep(5000);
//refreshSthHere();
}
}.start();
You can use Handler like Tom Leese said or Java Timer
new Timer().schedule(new TimerTask() {
#Override
public void run() {
// this code will be executed after 2 seconds
}
}, 2000);
I know you can only change the text in tTxtViews from the UI thread but i cant seem to find a way to work with that.
I'll go in to a bit more details: I'm trying to have a TextView that displays the time passed, but I can't do it in a thread, or a method that keeps getting called.
can you help me with a way of doing this? because I'm pretty much out of ideas.
Thanks.
public class MainActivity extends Activity {
protected static final long TIMER_DELAY = 100;
private TextView tv;
protected Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.helloWorld);
handler = new Handler();
handler.post(timerTask);
}
private Runnable timerTask = new Runnable() {
public void run() {
Calendar now = Calendar.getInstance();
//format date time
tv.setText(String.format("%02d:%02d:%02d", now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND)));
//run again with delay
handler.postDelayed(timerTask, TIMER_DELAY);
}
};
}
I forgot add this, sorry. Don't forget do this:
#Override
public void onPause() {
if (handler != null)
handler.removeCallbacks(timerTask);
super.onPause();
}
And if you want resume app try this
#Override
public void onResume() {
super.onResume();
if (handler != null)
handler.post(timerTask);
}
Use this
new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do what you want.
}
});
}
}).start();
or use a Handler:
Runnable r = new Runnable() {
#Override
public void run() {
// Do what you want.
}
};
Handler mHandler = new Handler();
mHandler.post(r);