在Android开发中,创建可以随意拖动的桌面悬浮窗口(通常称为悬浮窗或者浮窗)需要用到`WindowManager`服务。以下是一个简化的示例,展示如何创建一个基本的悬浮窗口,并使其可以拖动。
首先,你需要在你的AndroidManifest.xml中添加必要的权限:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
...
>
...
<activity android:name=".MainActivity">
...
</activity>
...
</application>
</manifest>
然后,在代码中,你需要检查并请求`SYSTEM_ALERT_WINDOW`权限(从Android 6.0开始,这个权限需要在运行时请求):
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
private WindowManager windowManager;
private View floatingView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1234);
} else {
setupFloatingView();
}
}
private void setupFloatingView() {
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
floatingView = new View(this);
floatingView.setBackgroundColor(Color.RED); // 设置背景色
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, // 使用悬浮窗类型
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
floatingView.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(floatingView, params);
return true;
}
return false;
}
});
windowManager.addView(floatingView, params);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1234) {
if (Settings.canDrawOverlays(this)) {
setupFloatingView();
}
}
}
}
注意:
1. 这个示例创建了一个红色的悬浮窗口,你可以通过拖动来移动它。
2. 在Android 6.0(API 级别 23)及以上,`SYSTEM_ALERT_WINDOW`权限需要在用户设置中手动开启,上面的代码示例中包含了请求这个权限的逻辑。
3. `TYPE_APPLICATION_OVERLAY`是Android O(API 级别 26)引入的,用于替代之前版本的`TYPE_