我正在开发一个基于传感器的应用程序,其主要目的是检测电缆的磁场。如果电缆中有电流流动,那么它应该显示一些消息,当没有电流时,它也应该通知。使用下面的代码,它检测到电流,但问题是它也检测到金属场。如果有人知道解决方案,请告诉我。
public class MainActivity extends Activity implements SensorEventListener {
SensorManager sensorManager;
// static final int sensor = SensorManager.SENSOR_ORIENTATION;
private Sensor myCompassSensor;
private TextView outView,tesla1,voltage;
ImageView light1;
Vibrator v;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outView = (TextView) findViewById(R.id.output);
tesla1=(TextView)findViewById(R.id.tesla);
light1=(ImageView)findViewById(R.id.light);
voltage=(TextView)findViewById(R.id.voltage);
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// get sensor manager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// get compass sensor (ie magnetic field)
myCompassSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
// register to listen to sensors
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this, myCompassSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
// unregister
@Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this,myCompassSensor);
}
// Ignore for now
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
// this check is unnecessary with only one registered sensor
// but it's useful to know in case you need to add more sensors
synchronized (this)
{
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// int orientation = (int) event.values[0];
float azimuth = Math.round(event.values[0]);
float pitch = Math.round(event.values[1]);
float roll = Math.round(event.values[2]);
double tesla= Math.sqrt((azimuth*azimuth)+(pitch*pitch)+(roll*roll));
String out = String.format("X: %.2f\nY: %.2f\nZ: %.2f",
azimuth, pitch, roll);
String a=String.format("%2f", tesla);
Log.d("MAGENTIC---", out);
// outView.setText(out);
tesla1.setText(a);
if(tesla>=80)
{
v.vibrate(200);
light1.setBackgroundResource(R.drawable.voltage_on);
voltage.setText("Voltage Detected !");
}
else
{
light1.setBackgroundResource(R.drawable.voltage_off);
voltage.setText("No Voltage Found");
}
}
else
return;
}
}
}