用户组 
易积分1095
热心0
好评0

|
每次使用无障碍功能需要手动打开系统设置去开启,这样操作很麻烦,需要实现自动开启功能!大佬们,有能力的可以考虑做个类库,谢谢!
App开机自启动:
一、AndroidManifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
二、代码:
//实现自启动功能
package lock.guardian;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent thisIntent = new Intent(context, Guardian.class);//设置要启动的app
thisIntent.setAction("android.intent.action.MAIN");
thisIntent.addCategory("android.intent.category.LAUNCHER");
thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(thisIntent);
}
}
}
三、注意手机上的设置,在自启动管理功能中将你的app加入白名单。
注册成为无障碍服务:
一、AndroidManifest:
<service
android:name="LockGuardianService"
android:process="system"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
<!--android:label="@string/accessibility_service_label"-->
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
</service>
实现悬浮窗:
一、AndroidManifest:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW"/>
二、代码:
private void showFloatingWindow() {
if (Settings.canDrawOverlays(this)) {
// 获取WindowManager服务
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
// 新建悬浮窗控件
Button button = new Button(getApplicationContext());
//button.setText("Floating Window");
button.setBackgroundColor(Color.GREEN);
button.setAlpha(0.1f);
// 根据android版本设置悬浮窗类型
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
} else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
layoutParams.format = PixelFormat.RGBA_8888;
//设置大小
layoutParams.width = 140;
layoutParams.height = 140;
//设置位置
layoutParams.x = 0;
layoutParams.y = 788;
// 将悬浮窗控件添加到WindowManager
windowManager.addView(button, layoutParams);
}
}
三、很容易忽略的一点:在手机上设置这个app启用悬浮窗权限。
用代码判断的方法是在onCreate方法中加入:
//在启动服务之前,需要先判断一下当前是否允许开启悬浮窗,若无则发出提示并跳转到手动授权页面
if (!Settings.canDrawOverlays(this)) {
Toast.makeText(this, "当前无开启悬浮窗权限,请授权", Toast.LENGTH_SHORT);
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
}
|
|