一、无障碍服务开启
AccessibilityService是一个抽象类,应用需要创建Service来继承AccessibilityService并实现抽象方法。
1、创建HongBaoService.java
2、AndroidManifest.xml中声明并配置
<service
android:name="com.yhao.floatwindow.HongBaoService"
android:enabled="true"
android:exported="true"
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/qianghongbao"/>
</service>
3、无障碍服务配置文件
android:resource="@xml/qianghongbao"是无障碍服务的配置文件,大概内容如下
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeAllMask"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagReportViewIds|flagRetrieveInteractiveWindows"
android:canPerformGestures="true"
android:canRetrieveWindowContent="true"
android:description="@string/app_name"
android:notificationTimeout="100"
/>
qianghongbao.xml可以放置在res/xml目录下
4、启动无障碍服务
public static void startService(Context mContext){
LogUtil.e("startService shan,======"+HongBaoService.isStart());
if (!HongBaoService.isStart()) {
Intent intent=new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
Intent intent2=new Intent(Settings.ACTION_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
mContext.startActivity(intent);
} catch (Exception e) {
mContext.startActivity(intent2);
LogUtil.e("Exception e"+e.getMessage());
e.printStackTrace();
}
return;
}
}
二、悬浮框
可以通过WindowManager动态添加居于其他应用上面的悬浮框,TYPE_ACCESSIBILITY_OVERLAY类型悬浮窗可以在锁屏、安装应用状态保持显示,TYPE_APPLICATION_OVERLAY类型悬浮窗在锁屏、安装应用状态会隐藏。
FloatPhone(Context applicationContext, PermissionListener permissionListener) {
mContext = applicationContext;
mPermissionListener = permissionListener;
mWindowManager = (WindowManager) applicationContext.getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.format = PixelFormat.RGBA_8888;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
mLayoutParams.windowAnimations = 0;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mLayoutParams.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY;
// mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
TYPE_ACCESSIBILITY_OVERLAY类型悬浮框创建时要使用无障碍服务的context,否则程序会挂掉,报错信息Unable to add window -- token null is not valid; is Activity Running