FloatService:
package com.home.floatwindow; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.IBinder; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import com.home.testfolatwindow.R; public class FloatService extends Service { private WindowManager wm; private WindowManager.LayoutParams wmlp; private LinearLayout layout; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); createFloatView(); } private void createFloatView() { wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); wmlp = new WindowManager.LayoutParams(); wmlp.type = LayoutParams.TYPE_PHONE; // 设置图片格式,效果为背景透明 wmlp.format = PixelFormat.RGBA_8888; // 设置浮动窗口不可聚焦 wmlp.flags = LayoutParams.FLAG_NOT_FOCUSABLE; wmlp.gravity = Gravity.LEFT | Gravity.TOP; wmlp.x = 0; wmlp.y = 0; wmlp.width = WindowManager.LayoutParams.WRAP_CONTENT; wmlp.height = WindowManager.LayoutParams.WRAP_CONTENT; layout = getLayout(); wm.addView(layout, wmlp); layout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); ImageView iv = (ImageView) layout.findViewById(1); iv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.i("onClick", "onClick"); } }); iv.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // getRawX是触摸位置相对于屏幕的坐标,getX是相对于按钮的坐标 wmlp.x = (int) event.getRawX() - layout.getMeasuredWidth() / 2; // 减25为状态栏的高度 wmlp.y = (int) event.getRawY() - layout.getMeasuredHeight() / 2 - 25; wm.updateViewLayout(layout, wmlp); return false; } }); } private LinearLayout getLayout() { LinearLayout layout = new LinearLayout(this); ImageView iv = new ImageView(this); iv.setBackgroundResource((R.drawable.ic_launcher)); iv.setId(1); layout.addView(iv); return layout; } @Override public void onDestroy() { super.onDestroy(); if (layout != null) { // 移除悬浮窗口 wm.removeView(layout); } } }
权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />