public class ProximityService extends Service implements SensorEventListener{
boolean hasproximity=false;
SensorManager mSensorManager;
AudioManager am;
Sensor psensor;
public ProximityService() {
}
@Override
public void onCreate() {
super.onCreate();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if(mSensorManager.getSensorList(Sensor.TYPE_PROXIMITY).size()>0) {
Toast.makeText(getApplicationContext(),"Proximity Sensor Detected",Toast.LENGTH_SHORT).show();
hasproximity=true;
psensor=mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
Toast.makeText(getBaseContext(), "sensor event listener addded", Toast.LENGTH_SHORT).show();
mSensorManager.registerListener(this,psensor,SensorManager.SENSOR_DELAY_UI);
} else {
hasproximity=false;
Toast.makeText(getApplicationContext(),"No Proximity Sensor",Toast.LENGTH_SHORT).show();
stopSelf();
}
}
@Override
public void onDestroy() {
super.onDestroy();
mSensorManager.unregisterListener(this);
Toast.makeText(getBaseContext(), "service destroyed", Toast.LENGTH_SHORT).show();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float vals[]=event.values;
float x; // light value is 0.0 then it is dark
x=vals[0];
Toast.makeText(getBaseContext(), "light:"+x, Toast.LENGTH_SHORT).show();
if(x == 0.0) {
Toast.makeText(getBaseContext(), "prox closed", Toast.LENGTH_SHORT).show();
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
} else {
Toast.makeText(getBaseContext(), "prox open", Toast.LENGTH_SHORT).show();
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}
}
如果接近传感器被覆盖,此代码用于将手机振铃模式从振铃更改为振动,即接近传感器接收的光值变为零。
问题是如果我们覆盖接近传感器时手机已经响铃,那么手机将进入静音模式,而不是振动模式。
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:0)
您可以使用此代码进行更改,使用> = Jerry Bean版本:
Settings.System.putInt(getContentResolver(), "vibrate_when_ringing", 0); //vibrate off
Settings.System.putInt(getContentResolver(), "vibrate_when_ringing", 1); //vibrate on
请记住添加权限:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />