Karthik
Karthik

Reputation: 5040

Android Is It possible to use Thread.sleep(60000) without getting ANR

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?

Upvotes: 0

Views: 1271

Answers (3)

UperOne
UperOne

Reputation: 195

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();
   });
}

Upvotes: 0

selbie
selbie

Reputation: 104549

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.

Upvotes: 1

cliffroot
cliffroot

Reputation: 1691

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);

Upvotes: 1

Related Questions