通过处理程序调用活动内的另一个活动函数不起作用

时间:2013-04-29 06:54:43

标签: java android android-handler

我想从其他活动开始CountDownTimer。我使用处理程序来做到这一点,但它不起作用。我做错了哪一部分?这是我的代码:

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

}
}

为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

initHandler()方法中,将switch案例中的条件从switch (msg.arg1)更改为switch (msg.what)

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