本文已授权「玉刚说」微信公众号独家发布
引入
最近在做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" />
设置页效果图:
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>)会在系统中注册,用户可以在手机系统辅助功能开启页看到该描述:
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