0

I want to start a CountDownTimer from another activity. I use handlers to do that, but it doesn't work. Which part am I doing wrong? This is my code:

activity1.java :

public class Activity1 extends Activity {
public static Handler mHandler; 

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initHandler();
mHandler.sendEmptyMessage(1);

startActivity(new Intent(Activity1.this, Activity2.class));
}

private void initHandler(){
mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch (msg.arg1) {
        case 1:
            mCountDownTimer.start();
            break;
        }
    }
};
}

private CountDownTimer mCountDownTimer = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
    Toast.makeText(Activity1.this, "Count is: "+ millisUntilFinished/1000,    Toast.LENGTH_SHORT).show();
}

@Override
public void onFinish() {
    // TODO Auto-generated method stub

}
};
}

activity2.java :

public class Activity2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Activity1.mHandler.sendEmptyMessage(1);

}
}

Why is this not working?

Mahm00d
  • 3,881
  • 8
  • 44
  • 83
Fcoder
  • 9,066
  • 17
  • 63
  • 100

1 Answers1

1

In your initHandler() method, change your condition in switch case from switch (msg.arg1) to switch (msg.what)

According to Android Developer site sendEmptyMessage(int) Sends a Message containing only the what value.

AnujMathur_07
  • 2,586
  • 2
  • 18
  • 25