2016-11-12 103 views
1

應用程序具有一個可以打開和關閉屏幕亮度的圖像按鈕,但是一次開啓和關閉屏幕亮度後,按鈕不再工作。有沒有人有想法,代碼有什麼問題?打開和關閉一次後按鈕停止功能

import android.provider.Settings; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.ImageButton; 

public class ScreenFlashlight extends AppCompatActivity { 
    private static String tag; 
    private static final String TAG = tag ; 
    private boolean brightnessOnOff; 
    private ImageButton screenFlashOnOffButton; 

    public ScreenFlashlight() throws Settings.SettingNotFoundException { 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_screen_flashlight); 
     screenFlashOnOffButton = (ImageButton) findViewById(R.id.flashOnOffButton); 
     brightnessOnOff = false; 


    } 
    public void screenFlashButtonClicked(View view) { 

      try { 
       if (brightnessOnOff) { 

        turnBrightnessOff(); 
        Log.d(TAG, "screenFlashButtonClicked: "); 
       } else { 
        brightnessOnOff = true; 
        turnBrightnessOn(); 
        Log.d(TAG, "screenFlashButtonClicked: "); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

    } 



    private void turnBrightnessOn() { 
     try { 
      screenFlashOnOffButton.setImageResource(R.drawable.screenonbutton); 
      int currentBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); 
      //Screen refresh to add brightness 

      WindowManager.LayoutParams lp = getWindow().getAttributes(); 
      lp.screenBrightness = currentBrightness/ 100.0f; 
      getWindow().setAttributes(lp); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private void turnBrightnessOff() { 
     try { 
      screenFlashOnOffButton.setImageResource(R.drawable.screenoffbutton); 
      int currentBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); 
      //Refresh screen 

      WindowManager.LayoutParams lpp = getWindow().getAttributes(); 
      lpp.screenBrightness = currentBrightness; 
      getWindow().setAttributes(lpp); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

回答

1

你從來沒有設置brightnessOnOff爲假時,亮度是關閉的,所以你按下按鈕後第一時間就會產生價值true。因此,您的代碼每次都會輸入if塊。當您關閉亮度時,需要做的是將brightnessOnOff設置爲false,並在再次打開亮度時將其設置爲true。基本上,您需要在truefalse之間替換brightnessOnOff以使其正常工作