我写了一个简单的活动来监听接近传感器(http://thecodeartist.blogspot.co.il/2011/01/proximity-sensor-on-android-gingerbread.html),我正在尝试测试它我的模拟器。该应用程序可在真实设备上运行(在 Nexus 4 上进行了检查)。
我一直在某处阅读,我应该修改 DDMS 中“位置控制”中的一些值以调用该警报(例如,https://stackoverflow.com/questions/15048559/can-i-test-proximity-alert- in-the-emulator),但我仍然不明白 - 位置与接近传感器有何关系,应该只提醒“远”或“近”?
非常感谢您的帮助,谢谢。
这是我的代码(通用且简单):
package com.example.proximitysensor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximitySensor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(this, mProximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.values[0] == 0)
{
Toast.makeText(this, "near", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "far", Toast.LENGTH_LONG).show();
}
}
}