前言
悬浮框常用于手机助手,应用内全局控制等场景。
今天就来介绍如何实现悬浮框。
思路
- 使用WindowManager可以在屏幕上添加自定义view。
- Android api 23以上需要申请悬浮窗权限。
- 由于悬浮框不受Activity影响,甚至程序关闭仍能存在,所以悬浮框运行在Service中。
- 将悬浮框与Serivce的生命周期绑定就可以通过stopService可以关闭悬浮框。
实现
具体实现不难,请看代码。
Avtivty
public class MainActivity extends AppCompatActivity {
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(MainActivity.this, FloatingService.class);
findViewById(R.id.show).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
startService(intent);
} else {
startFloatingService();
}
}
});
findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (intent != null) {
stopService(intent);
}
}
});
}
@RequiresApi(api = Build.VERSION_CODES.M)
public void startFloatingService() {
if (ActivityUtil.isServiceWork(this, "com.demon.suspensionbox.FloatingService")) {//防止重复启动
Toast.makeText(this, "已启动!", Toast.LENGTH_SHORT).show();
return;
}
if (!Settings.canDrawOverlays(this)) {
Toast.makeText(this, "当前无权限,请授权", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
} else {
startService(intent);
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (!Settings.canDrawOverlays(this)) {
Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
startService(intent);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示悬浮框" />
<Button
android:id="@+id/dismiss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="隐藏悬浮框" />
</LinearLayout>
Service
public class FloatingService extends Service {
private static final String TAG = "FloatingService";
private WindowManager windowManager;
private WindowManager.LayoutParams layoutParams;
private View floatView;
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layoutParams = new WindowManager.LayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
layoutParams.format = PixelFormat.RGBA_8888;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
layoutParams.gravity = Gravity.LEFT;//悬浮框在布局的位置
layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;//悬浮窗的宽,不指定则无法滑动
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;//悬浮窗的高,不指定则无法滑动
//layoutParams.x = 0; //初始位置的x坐标
//layoutParams.y = 0; //初始位置的y坐标
floatView = new View(getApplicationContext()); // 不依赖activity的生命周期
floatView = View.inflate(getApplicationContext(), R.layout.float_view, null);
final ImageView ivClose = floatView.findViewById(R.id.close);
ivClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopSelf();//关闭当前服务
}
});
floatView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ivClose.getVisibility() == View.GONE) {
ivClose.setVisibility(View.VISIBLE);
} else {
ivClose.setVisibility(View.GONE);
}
}
});
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showFloatingWindow();
return super.onStartCommand(intent, flags, startId);
}
private void showFloatingWindow() {
windowManager.addView(floatView, layoutParams);
floatView.setOnTouchListener(new FloatingOnTouchListener());
}
private class FloatingOnTouchListener implements View.OnTouchListener {
private int x;
private int y;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = (int) event.getRawX();
y = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int nowX = (int) event.getRawX();
int nowY = (int) event.getRawY();
int movedX = nowX - x;
int movedY = nowY - y;
x = nowX;
y = nowY;
layoutParams.x = layoutParams.x + movedX;
layoutParams.y = layoutParams.y + movedY;
//Log.i(TAG, "onTouch: " + layoutParams.x + " " + layoutParams.y);
windowManager.updateViewLayout(view, layoutParams);
break;
default:
break;
}
return false;
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (floatView != null) {
windowManager.removeViewImmediate(floatView);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/close"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/close"
android:visibility="gone" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@mipmap/ic_launcher_round" />
</LinearLayout>