我正在尝试制作一个仅在覆盖接近传感器时播放声音的应用程序,但是当传感器被揭开时它会再次播放声音。
如何在声音被遮盖时播放声音并且在发现声音时不播放任何声音?
public class MainActivity extends ActionBarActivity {
SensorManager sm;
Sensor ProximitySensor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
ProximitySensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
sm.registerListener(proximitySensorEventListener,
ProximitySensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
SensorEventListener proximitySensorEventListener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
call();
}
}
};
private void call() {
ImageView im = (ImageView) findViewById(R.id.nfcoff);
ImageView imm = (ImageView) findViewById(R.id.buz);
if (im.getVisibility() == View.INVISIBLE && imm.getVisibility() == View.VISIBLE) {
mp = MediaPlayer.create(this, R.raw.ovnoise);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} else
if (im.getVisibility() == View.INVISIBLE && imm.getVisibility() == View.INVISIBLE) {
mp = MediaPlayer.create(this, R.raw.ovbus);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
}
答案 0 :(得分:0)
我添加了一个int计数来计算调用该方法的次数,并添加了一个if语句,该语句表示只有当int是奇数时才能调用该方法,使得该方法每隔一次被称为无效。
{{1}}