第一步:创建一个项目。
第二步:创建一个service class,继承 Service
public class MyService extends Service {
private static final String TAG = "MyService";
//要引用的布局文件.
ConstraintLayout toucherLayout;
//布局参数.
WindowManager.LayoutParams params;
//实例化的WindowManager.
WindowManager windowManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "into MyService onCreate");
//OnCreate中来生成悬浮窗.
createToucher();
}
private void createToucher() {
//赋值WindowManager&LayoutParam.
params = new WindowManager.LayoutParams();
windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
//设置type.系统提示型窗口,一般都在应用程序窗口之上.
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//设置效果为背景透明.
//params.format = PixelFormat.RGBA_8888;
//设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//设置窗口初始停靠位置.
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 0;
//设置悬浮窗口长宽数据.
//注意,这里的width和height均使用px而非dp.这里我偷了个懒
//如果你想完全对应布局设置,需要先获取到机器的dpi
//px与dp的换算为px = dp * (dpi / 160).
params.width = 200;
params.height = 200;
LayoutInflater inflater = LayoutInflater.from(getApplication());
//获取浮动窗口视图所在布局.
toucherLayout = (ConstraintLayout) inflater.inflate(R.layout.activity_main, null);
//添加toucherlayout
windowManager.addView(toucherLayout, params);
}
}
第三步:注册我们创建的Service,并相应添加权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
<application
....
<service android:name=".MyService" />
</application>
第四步:启动Service
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
if (Settings.canDrawOverlays(MainActivity.this)) {
Intent intent = new Intent(MainActivity.this, MyService.class);
Toast.makeText(MainActivity.this, "已开启Toucher", Toast.LENGTH_SHORT).show();
startService(intent);
finish();
} else {
//若没有权限,提示获取.
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
Toast.makeText(MainActivity.this, "需要取得权限以使用悬浮窗", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
} else {
//SDK在23以下,不用管.
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
finish();
}
}
最后,看下结果:
github: