启用飞行模式Onclick -Android

时间:2014-02-26 13:37:53

标签: android

我的项目中有一个切换按钮,我想要的是togglebutton应该打开飞行模式然后自动关闭它5秒后关闭。我找到了一个代码,但我不知道如何修改它以使用切换按钮

public void onClick(View v) {
    // check current state first
    boolean state = isAirplaneMode();
    // toggle the state
    toggleAirplaneMode(state);

    state = isAirplaneMode();
    // toggle the state
    toggleAirplaneMode(state);
    ser = new ServiceState();
    ser.setState(STATE_IN_SERVICE);
}

切换按钮

toggle = (ToggleButton) findViewById(R.id.tglbtn1);
toggle.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        if (toggle.isChecked()) {
            Toast.makeText(
                    getApplicationContext(),
                    "toggle button enabled",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    "toggle button disabled",   Toast.LENGTH_LONG).show();
        }
    }
});

}
}

2 个答案:

答案 0 :(得分:0)

看一下这个文档,它是关于Android上的ToggleButton管理: http://developer.android.com/guide/topics/ui/controls/togglebutton.html

可以帮助您了解它的工作原理。

那就是说,如此快速地停用/重新激活飞机模式的目的是什么?

要在x秒内执行任务,您可以使用Timer类: http://developer.android.com/reference/java/util/Timer.html

甚至更好: http://developer.android.com/reference/java/util/concurrent/ScheduledThreadPoolExecutor.html

答案 1 :(得分:0)

我不确定你的方法正在做什么完全,所以我猜测一下细节。但你应该能够填补空白:

public void onClick(View v) {
    // check current state first
    boolean state = isAirplaneMode();
    // toggle the state
    toggleAirplaneMode(state);

    state = isAirplaneMode();
    // toggle the state
    toggleAirplaneMode(state);
    ser = new ServiceState();
    ser.setState(STATE_IN_SERVICE);

    // you might want to disable the button here

    // change state back after 5s
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            // TODO actually change the state variable
            // and toggle back the airplane mode
            // if you disabled the button, enable it here
        }
    }, 5000);
}
相关问题