android手机悬浮窗设计
假装多好123 人气:0最近项目中有个需求就是要在android 系统桌面上写一个悬浮球,并使其具有返回,进到主页,打开设置等功能。类似于华为手机的悬浮球。这里主要用到windowManager来实现。
1.先来看看效果图
主页的小圆点
点击小圆点之后展开,然后可以模拟虚拟按键,返回等功能。全局有效。
2.一步步来实现
1.首先这个要常住在桌面,故得写在一个服务里面里面。服务的启动可以通过开机广播,或者在Activity 中启动后直接finish 掉,这里都做一下。方便点击测试
public class MainActivity extends Activity { private static final int NOT_NOTICE = 2;//如果勾选了不再询问 private AlertDialog alertDialog; private AlertDialog mDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(MainActivity.this, FloatWindowService.class); startService(intent); finish(); } }
public class FwBroadcastReceiver extends BroadcastReceiver { public static final String TAG = "FwBroadcastReceiver"; public static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"; public static final String ACTION_STASRT_FLAOTWINDOW = "android.intent.action.start.FlaotWindow"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "intent:" + intent.getAction()); startFloatWindowService(context); } private void startFloatWindowService(Context context) { Intent intent = new Intent(context, FloatWindowService.class); context.startService(intent); } }
2.FloatWindowService 中去创建悬浮球
public class FloatWindowService extends Service { /** * 用于在线程中创建或移除悬浮窗。 */ private Handler handler = new Handler(); /** * 定时器,定时进行检测当前应该创建还是移除悬浮窗。 */ private Timer timer; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 开启定时器,每隔0.5秒刷新一次 if (timer == null) { timer = new Timer(); timer.scheduleAtFixedRate(new RefreshTask(), 0, 500); } return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); // Service被终止的同时也停止定时器继续运行 if (timer != null) { timer.cancel(); timer = null; } } class RefreshTask extends TimerTask { @Override public void run() { // 没有悬浮窗显示,则创建悬浮窗。 if ( !MyWindowManager.isWindowShowing()) { handler.post(new Runnable() { @Override public void run() { MyWindowManager.createSmallWindow(getApplicationContext()); } }); } }
3. 核心部分,创建大小悬浮窗
public class MyWindowManager { /** * 小悬浮窗View的实例 */ private static FloatWindowSmallView smallWindow; /** * 大悬浮窗View的实例 */ private static FloatWindowBigView bigWindow; /** * 小悬浮窗View的参数 */ private static LayoutParams smallWindowParams; /** * 大悬浮窗View的参数 */ private static LayoutParams bigWindowParams; /** * 用于控制在屏幕上添加或移除悬浮窗 */ private static WindowManager mWindowManager; /** * 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。 * * @param context 必须为应用程序的Context. */ public static void createSmallWindow(Context context) { WindowManager windowManager = getWindowManager(context); int screenWidth = windowManager.getDefaultDisplay().getWidth(); int screenHeight = windowManager.getDefaultDisplay().getHeight(); if (smallWindow == null) { smallWindow = new FloatWindowSmallView(context); if (smallWindowParams == null) { smallWindowParams = new LayoutParams(); smallWindowParams.type = LayoutParams.TYPE_APPLICATION_OVERLAY; smallWindowParams.format = PixelFormat.RGBA_8888; smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE; // 注意这里的flag和type smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP; smallWindowParams.width = FloatWindowSmallView.viewWidth; smallWindowParams.height = FloatWindowSmallView.viewHeight; smallWindowParams.x = screenWidth; smallWindowParams.y = screenHeight / 2; } smallWindow.setParams(smallWindowParams); windowManager.addView(smallWindow, smallWindowParams); } } /** * 将小悬浮窗从屏幕上移除。 * * @param context 必须为应用程序的Context. */ public static void removeSmallWindow(Context context) { if (smallWindow != null) { WindowManager windowManager = getWindowManager(context); windowManager.removeView(smallWindow); smallWindow = null; } } /** * 创建一个大悬浮窗。位置为屏幕正中间。 * * @param context 必须为应用程序的Context. */ public static void createBigWindow(Context context) { WindowManager windowManager = getWindowManager(context); int screenWidth = windowManager.getDefaultDisplay().getWidth(); int screenHeight = windowManager.getDefaultDisplay().getHeight(); if (bigWindow == null) { bigWindow = new FloatWindowBigView(context); if (bigWindowParams == null) { bigWindowParams = new LayoutParams(); // bigWindowParams.x = screenWidth / 2 - FloatWindowBigView.viewWidth / 2; // bigWindowParams.y = screenHeight / 2 - FloatWindowBigView.viewHeight / 2; bigWindowParams.type = LayoutParams.TYPE_APPLICATION_OVERLAY; bigWindowParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE; // 这里的flag,如果不加这个,这这个界面的返回键(上面实际图的返回按钮)则没有作用,因为这个界面会消耗这个模拟的返回按键 bigWindowParams.format = PixelFormat.RGBA_8888; bigWindowParams.gravity = Gravity.RIGHT; bigWindowParams.width = FloatWindowBigView.viewWidth; bigWindowParams.height = FloatWindowBigView.viewHeight; } windowManager.addView(bigWindow, bigWindowParams); } } /** * 将大悬浮窗从屏幕上移除。 * * @param context 必须为应用程序的Context. */ public static void removeBigWindow(Context context) { if (bigWindow != null) { WindowManager windowManager = getWindowManager(context); windowManager.removeView(bigWindow); bigWindow = null; } } /** * 是否有悬浮窗(包括小悬浮窗和大悬浮窗)显示在屏幕上。 * * @return 有悬浮窗显示在桌面上返回true,没有的话返回false。 */ public static boolean isWindowShowing() { return smallWindow != null || bigWindow != null; } /** * 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。 * * @param context 必须为应用程序的Context. * @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。 */ private static WindowManager getWindowManager(Context context) { if (mWindowManager == null) { mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); } return mWindowManager; }
4.小悬浮窗布局
public class FloatWindowSmallView extends LinearLayout { /** * 记录小悬浮窗的宽度 */ public static int viewWidth; /** * 记录小悬浮窗的高度 */ public static int viewHeight; /** * 记录系统状态栏的高度 */ private static int statusBarHeight; /** * 用于更新小悬浮窗的位置 */ private WindowManager windowManager; /** * 小悬浮窗的参数 */ private WindowManager.LayoutParams mParams; /** * 记录当前手指位置在屏幕上的横坐标值 */ private float xInScreen; /** * 记录当前手指位置在屏幕上的纵坐标值 */ private float yInScreen; /** * 记录手指按下时在屏幕上的横坐标的值 */ private float xDownInScreen; /** * 记录手指按下时在屏幕上的纵坐标的值 */ private float yDownInScreen; /** * 记录手指按下时在小悬浮窗的View上的横坐标的值 */ private float xInView; /** * 记录手指按下时在小悬浮窗的View上的纵坐标的值 */ private float yInView; public FloatWindowSmallView(Context context) { super(context); windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); LayoutInflater.from(context).inflate(R.layout.float_window_small, this); View view = findViewById(R.id.small_window_layout); viewWidth = view.getLayoutParams().width; viewHeight = view.getLayoutParams().height; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度 xInView = event.getX(); yInView = event.getY(); xDownInScreen = event.getRawX(); yDownInScreen = event.getRawY() - getStatusBarHeight(); xInScreen = event.getRawX(); yInScreen = event.getRawY() - getStatusBarHeight(); Log.d("xct","down"+"xInView:"+xInView+"yInView:"+yInView+"xInScreen:"+xInScreen+"yInScreen:"+yInScreen); break; case MotionEvent.ACTION_MOVE: xInScreen = event.getRawX(); yInScreen = event.getRawY() - getStatusBarHeight(); // 手指移动的时候更新小悬浮窗的位置 Log.d("xct","move"+"xInView:"+xInView+"yInView:"+yInView+"xInScreen:"+xInScreen+"yInScreen:"+yInScreen); updateViewPosition(); break; case MotionEvent.ACTION_UP: // 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。 Log.d("xct","up"+"xInView:"+xInView+"yInView:"+yInView+"xInScreen:"+xInScreen+"yInScreen:"+yInScreen); if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) { openBigWindow(); } break; default: break; } return true; } /** * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。 * * @param params * 小悬浮窗的参数 */ public void setParams(WindowManager.LayoutParams params) { mParams = params; } /** * 更新小悬浮窗在屏幕中的位置。 */ private void updateViewPosition() { mParams.x = (int) (xInScreen - xInView); mParams.y = (int) (yInScreen - yInView); windowManager.updateViewLayout(this, mParams); } /** * 打开大悬浮窗,同时关闭小悬浮窗。 */ private void openBigWindow() { MyWindowManager.createBigWindow(getContext()); MyWindowManager.removeSmallWindow(getContext()); } /** * 用于获取状态栏的高度。 * * @return 返回状态栏高度的像素值。 */ private int getStatusBarHeight() { if (statusBarHeight == 0) { try { Class<?> c = Class.forName("com.android.internal.R$dimen"); Object o = c.newInstance(); Field field = c.getField("status_bar_height"); int x = (Integer) field.get(o); statusBarHeight = getResources().getDimensionPixelSize(x); } catch (Exception e) { e.printStackTrace(); } } return statusBarHeight; } }
5.大悬浮窗布局
public class FloatWindowBigView extends LinearLayout{ /** * 记录大悬浮窗的宽度 */ public static int viewWidth; /** * 记录大悬浮窗的高度 */ public static int viewHeight; /** * 记录当前手指位置在屏幕上的横坐标值 */ private float xInScreen; /** * 记录当前手指位置在屏幕上的纵坐标值 */ private float yInScreen; private static int statusBarHeight; /** * 记录手指按下时在屏幕上的横坐标的值 */ private float xDownInScreen; /** * 记录手指按下时在屏幕上的纵坐标的值 */ private float yDownInScreen; /** * 记录手指按下时在小悬浮窗的View上的横坐标的值 */ private float xInView; /** * 记录手指按下时在小悬浮窗的View上的纵坐标的值 */ private float yInView; @Override public boolean onTouchEvent(MotionEvent event) { Log.d("xct","onTouchEvent"); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度 xInView = event.getX(); yInView = event.getY(); xDownInScreen = event.getRawX(); yDownInScreen = event.getRawY() - getStatusBarHeight(); xInScreen = event.getRawX(); yInScreen = event.getRawY() - getStatusBarHeight(); Log.d("xct", "down" + "xInView:" + xInView + "yInView:" + yInView + "xInScreen:" + xInScreen + "yInScreen:" + yInScreen); break; case MotionEvent.ACTION_MOVE: xInScreen = event.getRawX(); yInScreen = event.getRawY() - getStatusBarHeight(); // 手指移动的时候更新小悬浮窗的位置 Log.d("xct", "move" + "xInView:" + xInView + "yInView:" + yInView + "xInScreen:" + xInScreen + "yInScreen:" + yInScreen); break; case MotionEvent.ACTION_UP: // 如果手指离开屏幕时,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,则视为触发了单击事件。 if (xInView < 0 || yInView < 0 || yInView > 445){ ContronPresent.getInstance().closeBigFlaot(getContext()); } Log.d("xct", "up" + "xInView:" + xInView + "yInView:" + yInView + "xInScreen:" + xInScreen + "yInScreen:" + yInScreen); break; default: break; } return super.onTouchEvent(event); } public FloatWindowBigView(final Context context) { super(context); LayoutInflater.from(context).inflate(R.layout.float_window_big, this); View view = findViewById(R.id.big_window_layout); viewWidth = view.getLayoutParams().width; viewHeight = view.getLayoutParams().height; Button close = findViewById(R.id.close); Button back = findViewById(R.id.back); Button home = findViewById(R.id.home); Button rorate = findViewById(R.id.rorate); Button control = findViewById(R.id.control); close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 点击返回的时候,移除大悬浮窗,创建小悬浮窗 MyWindowManager.removeBigWindow(context); MyWindowManager.createSmallWindow(context); } }); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Thread(){ @Override public void run() { new Instrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } }.start(); } }); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("xct","去home页"); } }); rorate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); control.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("xct","控制中心"); } }); } private int getStatusBarHeight() { if (statusBarHeight == 0) { try { Class<?> c = Class.forName("com.android.internal.R$dimen"); Object o = c.newInstance(); Field field = c.getField("status_bar_height"); int x = (Integer) field.get(o); statusBarHeight = getResources().getDimensionPixelSize(x); } catch (Exception e) { e.printStackTrace(); } } return statusBarHeight; } @Override public boolean dispatchKeyEvent(KeyEvent event) { Log.i("xct", "dispatchKeyEvent: "+event.getKeyCode()); return true; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { Log.d("xct","dispatchTouchEvent"); return super.dispatchTouchEvent(ev); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { Log.d("xct","onKeyDown:"+keyCode); return super.onKeyDown(keyCode, event); } }
6.需要注意的
这里需要注意的是,一是权限问题,因为我是系统权限,故不用申请,如果第三方需要使用,则如果动态申请。
另外就是在这我这个例子中,大悬浮窗中的模拟返回按键,是回有按键传递的,故大悬浮窗的参数中必须加入 bigWindowParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE; 否则返回事件会传不下去。
加载全部内容