如何使用togglebutton打开和关闭android接近传感器

时间:2013-10-30 09:35:31

标签: android proximitysensor

我制作了一款使用接近传感器改变歌曲的MP3播放器应用程序。我决定更新它并添加使用切换按钮禁用传感器的功能。我尝试使用此代码:

 case R.id.toggleButton1:
            if (toggleButton1.isChecked()) 
            {
                sm.unregisterListener(this);
                Toast.makeText(getBaseContext(), "Proximity Sensor Off!",
                        Toast.LENGTH_SHORT).show();
            }

            break;

我在代码中进一步注册了监听器。当我现在运行应用程序时,监听器已被禁用。我希望默认情况下启用它,除非用户选择切换按钮。任何帮助将不胜感激......非常感谢!

2 个答案:

答案 0 :(得分:0)

sm.unregisterListener(); 因为你可能是从onClickListener调用它,这个意味着实际的OnClickListener而不是proximysensor监听器

答案 1 :(得分:0)

这可能对你有帮助......

public class SensorActivity extends Activity implements SensorEventListener,
        CompoundButton.OnCheckedChangeListener {
    private ToggleButton toggleButton;
    private SensorManager sensorManager;
    private Sensor proximitySensor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
        toggleButton.setOnCheckedChangeListener(this);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        proximitySensor = sensorManager
                .getDefaultSensor(Sensor.TYPE_PROXIMITY);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (proximitySensor != null) {
            sensorManager.registerListener(this, proximitySensor,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        if (isChecked && proximitySensor != null) {
            sensorManager.registerListener(this, proximitySensor,
                    SensorManager.SENSOR_DELAY_NORMAL);
        } else {
            sensorManager.unregisterListener(this);
        }
    }
}