我是Android Studio的新手,我只是使用在线资源来学习Android。我想制作一个当加速度计的x轴更改时播放蜂鸣声的应用程序。
这是我的代码:
package com.hamzah.accelerometer;
import android.content.res.AssetFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.media.MediaPlayer;
public class MainActivity extends AppCompatActivity implements
SensorEventListener {
private float mLastX, mLastY, mLastZ;
private boolean mInitialized;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInitialized = false;
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
final MediaPlayer player = MediaPlayer.create(this, R.raw.beep);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event){
TextView tvX= (TextView)findViewById(R.id.x_axis);
TextView tvY= (TextView)findViewById(R.id.y_axis);
TextView tvZ= (TextView)findViewById(R.id.z_axis);
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if (!mInitialized) {
mLastX = x;
mLastY = y;
mLastZ = z;
tvX.setText("0.0");
tvY.setText("0.0");
tvZ.setText("0.0");
mInitialized = true;
} else {
float deltaX = Math.abs(mLastX - x);
float deltaY = Math.abs(mLastY - y);
float deltaZ = Math.abs(mLastZ - z);
float NOISE = (float) 2.0;
if (deltaX < NOISE) deltaX = (float)0.0;
if (deltaY < NOISE) deltaY = (float)0.0;
if (deltaZ < NOISE) deltaZ = (float)0.0;
mLastX = x;
mLastY = y;
mLastZ = z;
tvX.setText(Float.toString(deltaX));
tvY.setText(Float.toString(deltaY));
tvZ.setText(Float.toString(deltaZ));
if (deltaX > deltaY) {
player.start();
} else {
iv.setVisibility(View.INVISIBLE);
}
}
}
}
我不知道该怎么做,如果x轴的加速度大于y轴的加速度,则应该发出哔声(我已将其上传到原始文件夹中)。 / p>
player.start()
中肯定存在问题,我不知道该如何编写代码。
答案 0 :(得分:1)
您正在尝试投射方法“ player.start();”。在onSensorChanged(SensorEvent事件)的主体内部。 您的对象播放器在onCreate(Bundle savedInstanceState)内部声明。因此只能在这里使用。 您必须声明
private final MediaPlayer player;
然后在onCreate中将其初始化
player = MediaPlayer.create(this, R.raw.beep);