1

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

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

            break;

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

4

2 回答 2

0

this may help you...

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);
        }
    }
}
于 2013-10-30T10:27:35.183 回答
0

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

于 2013-10-30T09:47:30.680 回答