7

I used postedDelayed method to refresh my Activity, which works fine. But the problem is that even when I press the Back button postdelayed method call back the previous activity..

//handler for 30000 milli-secs post delay refreshment of the activity

mHandler.postDelayed(new Runnable() {
public void run() {
               dostuff();

        }
            }, 30000);
    }

protected void dostuff() {
Intent intent = getIntent();
finish();startActivity(intent);
Toast.makeText(getApplicationContext(), "refreshed", Toast.LENGTH_LONG).show();
}

public void onBackPressed() {
        super.onBackPressed();
        finish();
        mHandler.removeCallbacks(null);
        }

protected void onStop() {
            mHandler.removeCallbacks(null);
        super.onStop();
    }
mavHarsha
  • 1,056
  • 10
  • 16

3 Answers3

6

you just use this it may be help you

   Runnable runobj=new Runnable() {
public void run()
{
 dostuff();

 }
  };
 mHandler.postDelayed(runobj, 30000);
   }
public void onBackPressed() 
{
super.onBackPressed();
mHandler.removeCallbacks(runobj);
}
Prabu
  • 1,441
  • 15
  • 20
3

A workaround for this is :

When doing the dostuff() method, just check whether the Activity.isFinising() and do. If it is finishing, just return.

When you back press, the activity will get finished and after that if the doStuff() executes, it will not do anything.

Eldhose M Babu
  • 14,382
  • 8
  • 39
  • 44
1

mHandler.removeCallbacks(null);. You are passing null as a parameter. Pass a Runnable onject . That should work.

public final void removeCallbacks (Runnable r)

Use the above.

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

http://developer.android.com/reference/android/os/Handler.html#removeCallbacks%28java.lang.Runnable%29

Edit : Example

Runnable runnable = new Runnable() {
@Override
public void run() {
    // execute some code
}
};

Handler handler = new Handler();  
handler.postDelayed(runnable, 10000);
handler.removeCallbacks(runnable);
Raghunandan
  • 132,755
  • 26
  • 225
  • 256