AccessibilityService帮你实现Android全局悬浮窗

本文已授权「玉刚说」微信公众号独家发布


效果图镇楼.gif

引入

最近在做Android大屏,70寸全触摸,基于Android 5.0的AOSP开发(手动落伍=_=),屏蔽三大虚拟金刚键,所以需要在屏幕两边固定侧边栏代替虚拟键并实现开机自启.
之前并没有开发过这种小工具,自然没啥经验,第一反应当然是去应用市场下载类似App体验一把,使用3个三方后发现它们都需要用户手动打开系统中的「无障碍」功能来模拟用户虚拟按键的点击事件,通过该突破口google一把,发现使用的是AccessibilityService这个直接继承自Service的子类.直接去https://developer.android.google.cn/找api,发现像微信红包助手之类的应用都是使用的该服务,厉害了OMG~用户全部授权后还不得分分钟模拟银行卡转账?!细思极恐后开始写bug,额不对,写代码.
项目地址:https://github.com/afterschoolkido/AndroidSideBar


开始

1.「开机启动」
这个好弄,监听开机广播嘛,定义一个DeviceBootReceiver继承自BroadcastReceiver,然后复写onReceive方法执行你的TODO list,我这儿的逻辑很简单了,开机检测授权,授权成功直接启动侧边栏,没有则进入授权设置页:

/**
 * device boot receiver
 *
 * @author majh
 */
public class DeviceBootReceiver extends BroadcastReceiver {

    private static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_BOOT)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if(PermissionUtil.isCanDrawOverlays(context) && PermissionUtil.isAccessibilityServiceEnable(context)) {
                    ServiceGo.launchAccessibility(context);
                }else {
                    MainPageGo(context);
                }
            }else {
                if(PermissionUtil.isAccessibilityServiceEnable(context)) {
                    ServiceGo.launchAccessibility(context);
                }else {
                    MainPageGo(context);
                }
            }
        }
    }

    private void MainPageGo(Context context) {
        Intent launch = new Intent(context,MainActivity.class);
        launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(launch);
    }

}

开机启动还需要在清单文件中申请下权限:

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

广播接收也需要注册下:

<receiver android:name=".DeviceBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.HOME"/>
            </intent-filter>
        </receiver>

需要注意:国产手机都内置了开机自启管家,包括像三星这样的大厂也有,就是为了对付国内乱启乱像,这里需要提示用户把侧边栏应用手动添加到电池优化白名单中~

2.「设置页」
设置页就是"悬浮窗"&"辅助功能"两个必要权限的检查,其中"悬浮窗"权限在Android M以下是直接给予权限的,这点注意下!

/**
 * home page
 *
 * @author majh
 */
public class MainActivity extends AppCompatActivity {

    private AppCompatButton mFlastWindowButton;
    private AppCompatButton mAccessibilityButton;
    private static final int FLAT_REQUEST_CODE = 213;
    private static final int ACCESSIBILITY_REQUEST_CODE = 438;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        mFlastWindowButton = findViewById(R.id.btn_flatwindow);
        mAccessibilityButton = findViewById(R.id.btn_accessibility);
        flatWindowVisible();
    }

    /**
     * flut button visible
     */
    private void flatWindowVisible() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // > M,grant permission
            if (PermissionUtil.isCanDrawOverlays(this)) {
                // permission authorized,service go,button gone
                mFlastWindowButton.setVisibility(View.GONE);
                accessibilityVisible();
            } else {
                // permission unauthorized,button visible
                mFlastWindowButton.setVisibility(View.VISIBLE);
                Toast.makeText(this,getString(R.string.permission_flatwindow_),Toast.LENGTH_SHORT).show();
            }
        } else {
            // < M,service go,gone
            mFlastWindowButton.setVisibility(View.GONE);
            accessibilityVisible();
        }
    }

    /**
     * Accessibility button visible
     */
    private void accessibilityVisible() {
        if(PermissionUtil.isAccessibilityServiceEnable(this)) {
            Toast.makeText(this,getString(R.string.permission_notice),Toast.LENGTH_SHORT).show();
            finish();
        }else {
            mAccessibilityButton.setVisibility(View.VISIBLE);
            Toast.makeText(this,getString(R.string.permission_accessibility_),Toast.LENGTH_SHORT).show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void goGetFlatWindow(View view) {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        startActivityForResult(intent,FLAT_REQUEST_CODE);
    }

    public void goGetAccessibility(View view) {
        Intent accessibleIntent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        startActivityForResult(accessibleIntent,ACCESSIBILITY_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == FLAT_REQUEST_CODE) {
            flatWindowVisible();
        }else if(requestCode == ACCESSIBILITY_REQUEST_CODE){
            accessibilityVisible();
        }
    }
}

悬浮窗和辅助功能需要申请以下权限:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
<uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
        tools:ignore="ProtectedPermissions" />

设置页效果图:


设置效果图.png

3.「辅助功能服务AccessibilityService」
这个是重点,通过该服务使用WindowManager直接addView两边的侧边栏,使用AccessibilityService需要一些固定设置,首先定义SideBarService继承AccessibilityService后复写其中的几个方法,然后需要在清单文件中注册如下:

<service
            android:name=".SideBarService"
            android:enabled="true"
            android:exported="true"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
            <intent-filter>
                <action android:name="android.accessibilityservice.AccessibilityService"/>
            </intent-filter>
            <meta-data
                android:name="android.accessibilityservice"
                android:resource="@xml/auto_reply_service_config"/>
        </service>

需要注意@xml/auto_reply_service_config这个xml文件,该文件用来设置AccessibilityService的一些基本配置项,当然也可以代码动态设置,我这儿没有特别需求,直接使用xml解析了:

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeNotificationStateChanged|typeWindowStateChanged|typeWindowContentChanged"
    android:accessibilityFeedbackType="feedbackGeneric"
    android:accessibilityFlags="flagDefault"
    android:canRetrieveWindowContent="true"
    android:notificationTimeout="100"
    android:description="@string/accessibility_description"/>

上面的@string/accessibility_description(<string name="accessibility_description">开启此功能打开侧边栏</string>)会在系统中注册,用户可以在手机系统辅助功能开启页看到该描述:


应用辅助功能描述.png

4.「侧边栏」
从动图可以看出,小箭头,侧边栏,音量,亮度控制条都是双份儿的,总不能复制两份儿一模一样的代码吧?!为了简便,我把小箭头,侧边栏,音量亮度做成三个对象,在对象内部对左右两边的不同表现做下处理即可,我真是个小机灵鬼^_~.

小箭头SideBarArrow代码如下:

/**
 * Arrow left & right
 *
 * @author majh
 */
public class SideBarArrow implements View.OnClickListener {

    private WindowManager.LayoutParams mParams;
    private LinearLayout mArrowView;
    private Context mContext;
    private boolean mLeft;
    private WindowManager mWindowManager;
    private SideBarService mSideBarService;
    private SideBarContent mContentBar;
    private LinearLayout mContentBarView;
    private LinearLayout mAnotherArrowView;

    public LinearLayout getView(Context context,boolean left,WindowManager windowManager,SideBarService sideBarService) {
        mContext = context;
        mLeft = left;
        mWindowManager = windowManager;
        mSideBarService = sideBarService;
        mParams = new WindowManager.LayoutParams();
        // compatible
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        // set bg transparent
        mParams.format = PixelFormat.RGBA_8888;
        // can not focusable
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mParams.x = 0;
        mParams.y = 0;
        // window size
        mParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        mParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // get layout
        LayoutInflater inflater = LayoutInflater.from(context);
        mArrowView = (LinearLayout) inflater.inflate(R.layout.layout_arrow, null);
        AppCompatImageView arrow = mArrowView.findViewById(R.id.arrow);
        arrow.setOnClickListener(this);
        if(left) {
            arrow.setRotation(180);
            mParams.gravity = Gravity.START | Gravity.CENTER_VERTICAL;
            mParams.windowAnimations = R.style.LeftSeekBarAnim;
        }else {
            mParams.gravity = Gravity.END | Gravity.CENTER_VERTICAL;
            mParams.windowAnimations = R.style.RightSeekBarAnim;
        }
        mWindowManager.addView(mArrowView,mParams);
        return mArrowView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.arrow:
                mArrowView.setVisibility(View.GONE);
                mAnotherArrowView.setVisibility(View.GONE);
                if(null == mContentBar || null == mContentBarView) {
                    mContentBar = new SideBarContent();
                    mContentBarView = mContentBar.getView(mContext,mLeft,mWindowManager,mParams,mArrowView,mSideBarService, mAnotherArrowView);
                }else {
                    mContentBarView.setVisibility(View.VISIBLE);
                }
                mContentBar.removeOrSendMsg(false,true);
                break;
        }
    }

    public void setAnotherArrowBar(LinearLayout anotherArrowBar) {
        mAnotherArrowView = anotherArrowBar;
    }

    public void launcherInvisibleSideBar() {
        mArrowView.setVisibility(View.VISIBLE);
        if(null != mContentBar || null != mContentBarView) {
            mContentBarView.setVisibility(View.GONE);
            mContentBar.removeOrSendMsg(true,false);
            mContentBar.clearSeekBar();
        }
    }

    /**
     * when AccessibilityService is forced closed
     */
    public void clearAll() {
        mWindowManager.removeView(mArrowView);
        if(null != mContentBar || null != mContentBarView) {
            mWindowManager.removeView(mContentBarView);
            mContentBar.clearSeekBar();
            mContentBar.clearCallbacks();
        }
    }
}

侧边栏SideBarContent代码如下:

/**
 * Sidebar left & right
 *
 * @author majh
 */
public class SideBarContent implements View.OnClickListener {

    private Context mContext;
    private boolean mLeft;
    private LinearLayout mContentView;
    private WindowManager mWindowManager;
    private LinearLayout mArrowView;
    private SideBarService mSideBarService;
    private ControlBar mControlBar;
    private LinearLayout mSeekBarView;
    private LinearLayout mAnotherArrowView;
    private int mTagTemp = -1;

    private static final int COUNT_DOWN_TAG = 1;
    private static final int COUNT_DWON_TIME = 5000;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case COUNT_DOWN_TAG:
                    goNormal();
                    break;
            }
        }
    };

    LinearLayout getView(Context context,
                         boolean left,
                         WindowManager windowManager,
                         WindowManager.LayoutParams params,
                         LinearLayout arrowView,
                         SideBarService sideBarService,
                         LinearLayout anotherArrowView) {
        mContext = context;
        mLeft = left;
        mWindowManager = windowManager;
        mArrowView = arrowView;
        mSideBarService = sideBarService;
        mAnotherArrowView = anotherArrowView;
        // get layout
        LayoutInflater inflater = LayoutInflater.from(context);
        mContentView = (LinearLayout) inflater.inflate(R.layout.layout_content, null);
        // init click
        mContentView.findViewById(R.id.tv_brightness).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_back).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_home).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_annotation).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_volume).setOnClickListener(this);
        mContentView.findViewById(R.id.tv_backstage).setOnClickListener(this);
        LinearLayout root = mContentView.findViewById(R.id.root);
        if(left) {
            root.setPadding(15,0,0,0);
        }else {
            root.setPadding(0,0,15,0);
        }
        mWindowManager.addView(mContentView,params);
        return mContentView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_brightness:
                removeOrSendMsg(true,true);
                brightnessPermissionCheck();
                break;
            case R.id.tv_back:
                removeOrSendMsg(true,true);
                clearSeekBar();
                mSideBarService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
                break;
            case R.id.tv_home:
                removeOrSendMsg(true,false);
                goNormal();
                mSideBarService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
                break;
            case R.id.tv_annotation:
                removeOrSendMsg(true,false);
                goNormal();
                annotationGo();
                break;
            case R.id.tv_volume:
                removeOrSendMsg(true,true);
                brightnessOrVolume(1);
                break;
            case R.id.tv_backstage:
                removeOrSendMsg(true,false);
                goNormal();
                mSideBarService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
                break;
        }
    }

    private void brightnessOrVolume(int tag) {
        if(mTagTemp == tag) {
            if(null != mSeekBarView) {
                removeSeekBarView();
            }else {
                addSeekBarView(tag);
            }
            return;
        }
        mTagTemp = tag;
        if(null == mControlBar) {
            mControlBar = new ControlBar();
        }
        if(null == mSeekBarView) {
            addSeekBarView(tag);
        }else {
            removeSeekBarView();
            addSeekBarView(tag);
        }
    }

    private void addSeekBarView(int tag) {
        mSeekBarView = mControlBar.getView(mContext,mLeft,tag,this);
        mWindowManager.addView(mSeekBarView, mControlBar.mParams);
    }

    private void removeSeekBarView() {
        if(null != mSeekBarView) {
            mWindowManager.removeView(mSeekBarView);
            mSeekBarView = null;
        }
    }

    private void arrowsShow() {
        mContentView.setVisibility(View.GONE);
        mArrowView.setVisibility(View.VISIBLE);
        mAnotherArrowView.setVisibility(View.VISIBLE);
    }

    void clearSeekBar() {
        if(null != mSeekBarView) {
            mWindowManager.removeView(mSeekBarView);
            mSeekBarView = null;
        }
    }

    private void goNormal() {
        arrowsShow();
        clearSeekBar();
    }

    private void annotationGo() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.android.notes", "com.android.notes.MainActivity"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            mContext.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(mContext, mContext.getString(R.string.app_not_find), Toast.LENGTH_SHORT).show();
        }
    }

    void removeOrSendMsg(boolean remove, boolean send) {
        if(remove) {
            mHandler.removeMessages(COUNT_DOWN_TAG);
        }
        if(send) {
            mHandler.sendEmptyMessageDelayed(COUNT_DOWN_TAG,COUNT_DWON_TIME);
        }
    }

    /**
     * when AccessibilityService is forced closed
     */
    void clearCallbacks() {
        if(null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    private void brightnessPermissionCheck() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionUtil.isSettingsCanWrite(mContext)) {
                goNormal();
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                Toast.makeText(mContext,mContext.getString(R.string.setting_modify_toast),Toast.LENGTH_LONG).show();
            }else {
                brightnessOrVolume(0);
            }
        }else {
            brightnessOrVolume(0);
        }
    }
}

可以看到在点击返回,主页,后台按钮时执行的分别是AccessibilityService对应的三个方法:

mSideBarService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);
mSideBarService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
mSideBarService.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);

该项目中之所以使用AccessibilityService就是为了调用这三个方法.

5.「音量亮度控制条」
音量亮度控制条使用的SeekBar,不过SeekBar默认横向,需要自定义VerticalSeekBar:

/**
 * A vertical SeekBar to control volume and brightness
 *
 * @author majh
 */
public class VerticalSeekBar extends AppCompatSeekBar {
    private boolean mIsDragging;
    private float mTouchDownY;
    private int mScaledTouchSlop;
    private boolean isInScrollingContainer = false;
    private Callback mCallback;

    public interface Callback {
        void onSeekBarDetached();
    }

    public boolean isInScrollingContainer() {
        return isInScrollingContainer;
    }

    public void setInScrollingContainer(boolean isInScrollingContainer) {
        this.isInScrollingContainer = isInScrollingContainer;
    }

    /**
     * On touch, this offset plus the scaled value from the position of the
     * touch will form the progress value. Usually 0.
     */
    float mTouchProgressOffset;

    public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

    }

    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VerticalSeekBar(Context context) {
        super(context);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldh, oldw);

    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec,
                                          int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        canvas.rotate(-90);
        canvas.translate(-getHeight(), 0);
        super.onDraw(canvas);
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (View.GONE == visibility && mCallback != null) {
            mCallback.onSeekBarDetached();
        }
    }

    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (isInScrollingContainer()) {
                    mTouchDownY = event.getY();
                } else {
                    setPressed(true);
                    invalidate();
                    onStartTrackingTouch();
                    trackTouchEvent(event);
                    attemptClaimDrag();
                    onSizeChanged(getWidth(), getHeight(), 0, 0);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (mIsDragging) {
                    trackTouchEvent(event);
                } else {
                    final float y = event.getY();
                    if (Math.abs(y - mTouchDownY) > mScaledTouchSlop) {
                        setPressed(true);
                        invalidate();
                        onStartTrackingTouch();
                        trackTouchEvent(event);
                        attemptClaimDrag();
                    }
                }
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                break;
            case MotionEvent.ACTION_UP:
                if (mIsDragging) {
                    trackTouchEvent(event);
                    onStopTrackingTouch();
                    setPressed(false);

                } else {
                    // Touch up when we never crossed the touch slop threshold
                    // should
                    // be interpreted as a tap-seek to that location.
                    onStartTrackingTouch();
                    trackTouchEvent(event);
                    onStopTrackingTouch();
                }
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                // ProgressBar doesn't know to repaint the thumb drawable
                // in its inactive state when the touch stops (because the
                // value has not apparently changed)
                invalidate();
                break;
        }
        return true;
    }

    private void trackTouchEvent(MotionEvent event) {
        final int height = getHeight();
        final int top = getPaddingTop();
        final int bottom = getPaddingBottom();
        final int available = height - top - bottom;
        int y = (int) event.getY();
        float scale;
        float progress = 0;
        if (y > height - bottom) {
            scale = 0.0f;
        } else if (y < top) {
            scale = 1.0f;
        } else {
            scale = (float) (available - y + top) / (float) available;
            progress = mTouchProgressOffset;
        }
        final int max = getMax();
        progress += scale * max;
        setProgress((int) progress);

    }

    /**
     * This is called when the user has started touching this widget.
     */
    void onStartTrackingTouch() {
        mIsDragging = true;
    }

    /**
     * This is called when the user either releases his touch or the touch is
     * canceled.
     */
    void onStopTrackingTouch() {
        mIsDragging = false;
    }

    private void attemptClaimDrag() {
        ViewParent p = getParent();
        if (p != null) {
            p.requestDisallowInterceptTouchEvent(true);
        }
    }

    @Override
    public synchronized void setProgress(int progress) {
        super.setProgress(progress);
        onSizeChanged(getWidth(), getHeight(), 0, 0);
    }
}

创建ControlBar类控制音量和亮度的分别调节:

/**
 * A bar to control brightness and volume
 *
 * @author majh
 */
class ControlBar {

    WindowManager.LayoutParams mParams;

    @SuppressLint("RtlHardcoded")
    LinearLayout getView(final Context context, boolean left, int tag, final SideBarContent sideBarContent) {
        mParams = new WindowManager.LayoutParams();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else {
            mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        mParams.format = PixelFormat.RGBA_8888;
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        mParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        mParams.gravity = Gravity.LEFT | Gravity.TOP;
        LayoutInflater inflater = LayoutInflater.from(context);
        @SuppressLint("InflateParams")
        LinearLayout seekBarLayout = (LinearLayout) inflater.inflate(R.layout.layout_seekbar, null);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        seekBarLayout.measure(w,h);
        // left or right seekbar
        if(left) {
            mParams.x = DisplayUtil.dp2px(context,120) - seekBarLayout.getMeasuredWidth();
            mParams.y = DisplayUtil.getScreenHeight(context) - DisplayUtil.dp2px(context,282);
            mParams.windowAnimations = R.style.LeftSeekBarAnim;
        }else {
            mParams.x = DisplayUtil.getScreenWidth(context) - DisplayUtil.dp2px(context,120);
            mParams.y = DisplayUtil.getScreenHeight(context) - DisplayUtil.dp2px(context,282);
            mParams.windowAnimations = R.style.RightSeekBarAnim;
        }
        VerticalSeekBar seekBar = seekBarLayout.findViewById(R.id.sb_);
        AppCompatImageView plus = seekBarLayout.findViewById(R.id.plus);
        AppCompatImageView less = seekBarLayout.findViewById(R.id.less);
        if(tag == 0) {
            // brightness control
            plus.setImageDrawable(context.getDrawable(R.drawable.ic_brightness_plus_));
            less.setImageDrawable(context.getDrawable(R.drawable.ic_brightness_less_));
            // brightness range 0~255
            seekBar.setMax(255);
            seekBar.setProgress(SystemBrightness.getBrightness(context));
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    SystemBrightness.setBrightness(context, progress);
                    sideBarContent.removeOrSendMsg(true,true);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
        }else if(tag == 1) {
            // volume control
            plus.setImageDrawable(context.getDrawable(R.drawable.ic_volume_plus_));
            less.setImageDrawable(context.getDrawable(R.drawable.ic_volume_less_));
            // volume range 0~15
            seekBar.setMax(15);
            seekBar.setProgress(SystemVolume.getVolume(context));
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    SystemVolume.setVolume(context, progress);
                    sideBarContent.removeOrSendMsg(true,true);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
        }
        return seekBarLayout;
    }
}

需要注意的是在Android系统中音量的调节范围是0-15,屏幕亮度的调节范围是0-255,其中调节系统屏幕亮度实际上是更改了系统的设置,需要较高的系统权限,所以在调节系统亮度之前需要检查是否授权:

private void brightnessPermissionCheck() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionUtil.isSettingsCanWrite(mContext)) {
                goNormal();
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                Toast.makeText(mContext,mContext.getString(R.string.setting_modify_toast),Toast.LENGTH_LONG).show();
            }else {
                brightnessOrVolume(0);
            }
        }else {
            brightnessOrVolume(0);
        }
    }

同时需要在清单文件中申请权限:

<uses-permission android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />

6.「细节」
ui方面,图片使用了vector,launch icon使用了adaptive icon,外加一些交互动画.


总结

不用AccessibilityService也可以实现三大虚拟按键的功能,具体代码如下:
「返回」

private void back() {
        new Thread() {
            @Override
            public void run() {
                Instrumentation inst = new Instrumentation();
                try {
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
  }

「主页」

 private void goHome() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        getContext().startActivity(intent);
    }

「任务」

private void openRecents() {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            try {
                Class serviceManagerClass = Class.forName("android.os.ServiceManager");
                Method getService = serviceManagerClass.getMethod("getService", String.class);
                IBinder retbinder = (IBinder) getService.invoke(serviceManagerClass, "statusbar");
                Class statusBarClass = Class.forName(retbinder.getInterfaceDescriptor());
                Object statusBarObject = statusBarClass.getClasses()[0].getMethod("asInterface", IBinder.class).invoke(null, new Object[]{retbinder});
                Method clearAll = statusBarClass.getMethod("toggleRecentApps");
                clearAll.setAccessible(true);
                clearAll.invoke(statusBarObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Intent intent = new Intent(getContext(), MyAccessibilityService.class);
            intent.putExtra("ACTION", 3);
            getContext().startService(intent);
        }
    }

可以看出,使用上面这些方法除了不太优雅还有兼容问题.

因为该应用是作为系统应用直接放入system/priv-app下的,也就是有root权限,如果你的手机有root权限,授权AccessibilityService可以使用如下代码:

/**
 * device boot receiver
 *
 * @author majh
 */
public class DeviceBootReceiver extends BroadcastReceiver {

    private static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_BOOT)) {
            if(!isStartAccessibilityServiceEnable(context)) {
                Settings.Secure.putString(context.getContentResolver(),
                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                        context.getPackageName() + "/" + context.getPackageName() + ".SideBarService");
                Settings.Secure.putInt(context.getContentResolver(),
                        Settings.Secure.ACCESSIBILITY_ENABLED,1);
            }
            ServiceGo.launchAccessibility(context);
        }
    }

    private boolean isStartAccessibilityServiceEnable(Context context){
        AccessibilityManager accessibilityManager =
                (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
        assert accessibilityManager != null;
        List<AccessibilityServiceInfo> accessibilityServices =
                accessibilityManager.getEnabledAccessibilityServiceList(
                        AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
        for (AccessibilityServiceInfo info : accessibilityServices) {
            if (info.getId().contains(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
}

至此,一个囫囵的Android侧边栏悬浮窗就完成了,是不是很简单?
项目地址:https://github.com/afterschoolkido/AndroidSideBar
CSDN地址:https://blog.csdn.net/nerv2013/article/details/88356693
欢迎star && fork

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,066评论 4 62
  • 石膏鼻子的外形可以看作是上窄下宽的椎体,上调子时要适当加深明暗交界线转折的地方,并加强过渡,形成面的转折。 1、画...
    追光柚子阅读 751评论 0 0
  • 秋天到了,路旁那片树林开始落叶了,一片、两片、三片……数也数不清,堆得满地都是。远远看去,就像树林下铺着一层...
    花落幽然阅读 378评论 0 5
  • 1.锻炼,哑铃,平板支撑 2.阅读 3.做习题 今日心得与体会:无论与谁谈话时,都不要旁若无人的滔滔不绝讲个不停,...
    帅印_d025阅读 161评论 0 0
  • 写一写喜欢的人吧。 从初中的懵懂开始,我就喜欢亲近我的人,当然,同桌多数是女的,还是青春的时候,都不懂什么,就是觉...
    雪夜迷途阅读 186评论 0 2