2014-11-04 84 views
2

我正在調用屏幕上,當用戶正在通話時需要在屏幕上啓用和禁用觸摸事件。在android上禁用屏幕觸摸通話

在此,我對我的行爲實施SensorEventListener並覆蓋onSensorChanged()方法:

public void onSensorChanged(SensorEvent sensorEvent) { 
    if(sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) { 
     if(sensorEvent.values[0] == 0) { //Sleep 
      sleepScreen(true); 
     } else { //Wake 
      sleepScreen(false); 
     } 
    } 
} 

下面是我sleepScreen()方法:

protected void sleepScreen(boolean on){ 
    if(on == true) { 
     WindowManager.LayoutParams params = getWindow().getAttributes(); 
     params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 
     getWindow().setAttributes(params); 
    } else { 
     WindowManager.LayoutParams params = getWindow().getAttributes(); 
     params.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; 
     getWindow().setAttributes(params); 
    } 

} 

的FLAG_NOT_TOUCHABLE工作正常禁用觸摸事件。但是,我無法再次重新啓用觸摸事件。

請幫忙!

回答

2

步驟1:通過實施SensorEventListener

public void onSensorChanged(SensorEvent sensorEvent) { 
    if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) { 
     if (sensorEvent.values[0] == 0) { //Sleep 
      sleepScreen(true); 
     } else { //Wake 
      sleepScreen(false); 
     } 
    } 
} 

步驟3覆蓋的方法::包括此中的onCreate調用的setContentView()

int powerValue = 0x00000020; 

    try { 
     powerValue = PowerManager.class.getClass().getField("PROXIMITY_SCREEN_OFF_WAKE_LOCK").getInt(null); 
    } catch (Throwable ignored) { 
    } 

    mPowerManager = (PowerManager) getSystemService(POWER_SERVICE); 
    mWakeLock = mPowerManager.newWakeLock(field, getLocalClassName()); 

步驟2之前添加本方法來禁用屏幕鎖定

protected void sleepScreen(boolean on) { 

     if (on == true) { 
      if (!mWakeLock.isHeld()) { 
       mWakeLock.acquire(); 
      } 
     } else { 
      if (mWakeLock.isHeld()) { 
       mWakeLock.release(); 
      } 
     } 
} 

第4步:添加之後鎖定權限的AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK" />