Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用懸浮窗進一步降低螢幕亮度、護眼過濾藍光(Android App 實作)

編輯:關於 Android 開發

用懸浮窗進一步降低螢幕亮度、護眼過濾藍光(Android App 實作)

專案網址:https://github.com/hwding/make-it-darker

歡迎 Star、Fork,以及任何建議與指教!

在全黑的環境下手機,眼睛非常容易疲勞;即使把亮度調到最低,長時間適應之後仍會覺得刺眼。為了解決這個痛點,可以善用 Android 的懸浮窗,把一層半透明的黑色 layout 覆蓋在螢幕上,進一步降低實際亮度;同時透過改變濾鏡顏色,還能過濾藍光等等。出於自身需求,我便動手寫了這麼一個小工具。

效果預覽:

以服務啟動懸浮窗:

package com.amastigote.darker.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.LinearLayout;
import com.amastigote.darker.R;
import com.amastigote.darker.model.DarkerSettings;

public class ScreenFilterService extends Service {
    static LinearLayout linearLayout;
    static WindowManager.LayoutParams layoutParams;
    static WindowManager windowManager;

    @Override
    public void onCreate() {
        super.onCreate();
        createScreenFilter();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (linearLayout != null)
            windowManager.removeView(linearLayout);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void createScreenFilter() {
        layoutParams = new WindowManager.LayoutParams();
        windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        layoutParams.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;

        LayoutInflater layoutInflater = LayoutInflater.from(getApplication());
        linearLayout = (LinearLayout) layoutInflater.inflate(R.layout.screen_filter, null);
        windowManager.addView(linearLayout, layoutParams);
        removeScreenFilter();
    }

    public static void updateScreenFilter(DarkerSettings darkerSettings) {
        layoutParams.screenBrightness = darkerSettings.getBrightness();
        layoutParams.alpha = darkerSettings.getAlpha();
        windowManager.updateViewLayout(linearLayout, layoutParams);
    }

    public static void removeScreenFilter() {
        layoutParams.screenBrightness = DarkerSettings.BRIGHTNESS_AUTO;
        layoutParams.alpha = DarkerSettings.ALPHA_MINIMUM;
        windowManager.updateViewLayout(linearLayout, layoutParams);
    }
}

ScreenFilterService.java

這裡要特別注意:為 layoutParams 設定 type 時用到的 TYPE_PRIORITY_PHONE,可以覆蓋螢幕上的一切內容,而關於此類型需要特定的權限申請(見下文說明)。

screenBrightness 是懸浮窗自身的亮度,這裡預設為最低的 0.0F;alpha 是懸浮窗 layout 的透明度,預設為 0.4F,最高設為 0.8F,以免全黑導致無法操作。updateScreenFilter() 方法用來讀取使用者在 App 控制面板上的設定並更新濾鏡;removeScreenFilter() 並不是移除濾鏡,而是把濾鏡亮度恢復為自動、透明度設為全透明,方便下次啟動濾鏡。

控制介面與權限處理:

package com.amastigote.darker.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amastigote.darker.R;
import com.amastigote.darker.model.DarkerSettings;
import com.amastigote.darker.service.ScreenFilterService;
import com.rtugeek.android.colorseekbar.ColorSeekBar;
import io.feeeei.circleseekbar.CircleSeekBar;

public class MainActivity extends AppCompatActivity {
    DarkerSettings currentDarkerSettings = new DarkerSettings();
    CircleSeekBar circleSeekBar_brightness;
    CircleSeekBar circleSeekBar_alpha;
    ColorSeekBar colorSeekBar;
    Switch aSwitch;
    Intent intent;

    @Override
    protected void onDestroy() {
        if (intent != null)
            stopService(intent);
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("make it darker!");
        setSupportActionBar(toolbar);
        DarkerSettings.initializeContext(getApplicationContext());

        checkPermissions();

        circleSeekBar_brightness = (CircleSeekBar) findViewById(R.id.cp_brightness_circleSeekBar);
        circleSeekBar_alpha = (CircleSeekBar) findViewById(R.id.cp_alpha_circleSeekBar);
        colorSeekBar = (ColorSeekBar) findViewById(R.id.cp_colorSeekBar);
        aSwitch = (Switch) findViewById(R.id.cp_useColor_switch);
        ToggleButton toggleButton = (ToggleButton) findViewById(R.id.cm_toggle_button);
        Button restore_settings_button = (Button) findViewById(R.id.cm_restore_settings_button);

        restoreLatestSettings();

        toggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (((ToggleButton) view).isChecked())
                    collectCurrentDarkerSettings();
                else
                    ScreenFilterService.removeScreenFilter();
            }
        });

        restore_settings_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DarkerSettings darkerSettings_default = DarkerSettings.getDefaultSettings();
                circleSeekBar_brightness.setCurProcess((int) (darkerSettings_default.getBrightness() * 100));
                circleSeekBar_alpha.setCurProcess((int) (darkerSettings_default.getAlpha() * 100));
                if (aSwitch.isChecked() != darkerSettings_default.isUseColor()) {
                    aSwitch.setChecked(darkerSettings_default.isUseColor());
                    AlphaAnimation alphaAnimation_1 = new AlphaAnimation(1, 0);
                    alphaAnimation_1.setDuration(300);
                    colorSeekBar.startAnimation(alphaAnimation_1);
                    colorSeekBar.setVisibility(View.INVISIBLE);
                }
            }
        });

        aSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (((Switch) view).isChecked()) {
                    AlphaAnimation alphaAnimation_0 = new AlphaAnimation(0, 1);
                    alphaAnimation_0.setDuration(300);
                    colorSeekBar.startAnimation(alphaAnimation_0);
                    colorSeekBar.setVisibility(View.VISIBLE);
                } else {
                    AlphaAnimation alphaAnimation_1 = new AlphaAnimation(1, 0);
                    alphaAnimation_1.setDuration(300);
                    colorSeekBar.startAnimation(alphaAnimation_1);
                    colorSeekBar.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    private void collectCurrentDarkerSettings() {
        currentDarkerSettings.setBrightness(((float) circleSeekBar_brightness.getCurProcess()) / 100);
        currentDarkerSettings.setAlpha(((float) circleSeekBar_alpha.getCurProcess()) / 100);
        currentDarkerSettings.setUseColor(aSwitch.isChecked());
        currentDarkerSettings.setColor(colorSeekBar.getColor());
        currentDarkerSettings.saveCurrentSettings();
        ScreenFilterService.updateScreenFilter(currentDarkerSettings);
    }

    private void restoreLatestSettings() {
        DarkerSettings latestDarkerSettings = DarkerSettings.getCurrentSettings();
        circleSeekBar_alpha.setCurProcess((int) (latestDarkerSettings.getAlpha() * 100));
        circleSeekBar_brightness.setCurProcess((int) (latestDarkerSettings.getBrightness() * 100));
        if (latestDarkerSettings.isUseColor()) {
            aSwitch.setChecked(true);
            colorSeekBar.setVisibility(View.VISIBLE);
        }
        colorSeekBar.setColorBarValue(latestDarkerSettings.getColor());
    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(getApplicationContext())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 0);
            } else
                prepareForService();
        } else
            prepareForService();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.canDrawOverlays(this))
                    prepareForService();
                else {
                    Toast.makeText(getApplicationContext(), "權限請求被拒絕 無法正常工作 :(", Toast.LENGTH_LONG).show();
                    finish();
                }
            }
        }
    }

    private void prepareForService() {
        intent = new Intent(getApplicationContext(), ScreenFilterService.class);
        startService(intent);
    }
}

MainActivity.java

高優先級的懸浮窗屬於敏感權限,Android 6.0 以上系統需要特別處理。啟動時,先呼叫 checkPermissions():當系統版本為 6.0 及以上時,透過包裝一個 Intent,讓 App 專門請求使用者授權此權限;返回後再透過接收 result 判斷是否已取得 drawOverlays 權限——若沒有則報錯並正常退出,若已取得則啟動 service。而當系統版本低於 6.0 時,則可直接喚起 service,由系統自動向使用者請求該權限。

相關參考文章:

https://pcedu.pconline.com.cn/692/6928996.html

https://blog.csdn.net/yangqingqo/article/details/48371123/

https://www.cnblogs.com/mengdd/p/3824782.html

另外需要在 manifest 中聲明權限:<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

特別要注意:在 startService 之後不能立即讀寫 ScreenFilterService 類別中的成員變數,否則會出現 null 異常。因此應先隨 App 一起自動啟動 service,並在 ScreenFilterService 的 onCreate 方法中呼叫 removeScreenFilter(),防止濾鏡自動生效。

此外還需注意:應在 manifest 中把 MainActivity 的啟動模式設為單例(singleTask/singleInstance),以免在子 Activity 透過 navigationIcon 返回主 Activity 時導致重啟,使濾鏡消失。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved