0
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);
        }
    }
}

此代码用于在接近传感器被覆盖时将电话铃声模式从响铃更改为振动,即接近传感器接收到的光值变为零。

问题是,如果当我们覆盖接近传感器时手机已经响起,那么手机将进入静音模式,而不是振动模式。

谁能帮我解决问题?

4

1 回答 1

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" />
于 2013-09-05T13:10:55.533 回答