Android 懸浮窗用法

这个例子演示创建、移除悬浮窗,并且监听OnTouch事件,获取手指移动距离来更新悬浮窗位置。

声明权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

注意:在MIUI上需要在”安全中心-授权管理-应用权限管理”打开“显示悬浮窗”开关,并重启应用。

创建悬浮窗管理类

/**
 * 悬浮窗管理类
 */
public class FloatingManager {

    private WindowManager mWindowManager;
    private static FloatingManager mInstance;
    private Context mContext;

    public static FloatingManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new FloatingManager(context);
        }
        return mInstance;
    }

    private FloatingManager(Context context) {
        mContext = context;
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);//获得WindowManager对象
    }

    /**
     * 添加悬浮窗
     * @param view
     * @param params
     * @return
     */
    protected boolean addView(View view, WindowManager.LayoutParams params) {
        try {
            mWindowManager.addView(view, params);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 移除悬浮窗
     * @param view
     * @return
     */
    protected boolean removeView(View view) {
        try {
            mWindowManager.removeView(view);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 更新悬浮窗参数
     * @param view
     * @param params
     * @return
     */
    protected boolean updateView(View view, WindowManager.LayoutParams params) {
        try {
            mWindowManager.updateViewLayout(view, params);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

悬浮窗view

/**
 * 悬浮窗view
 */
public class FloatingView extends FrameLayout {
    private Context mContext;
    private View mView;
    private ImageView mImageView;
    private int mTouchStartX, mTouchStartY;//手指按下时坐标
    private WindowManager.LayoutParams mParams;
    private FloatingManager mWindowManager;

    public FloatingView(Context context) {
        super(context);
        mContext = context.getApplicationContext();
        LayoutInflater mLayoutInflater = LayoutInflater.from(context);
        mView = mLayoutInflater.inflate(R.layout.floating_view, null);
        mImageView = (ImageView) mView.findViewById(R.id.imageview);
        mImageView.setImageResource(R.drawable.img_loading);
        mImageView.setOnTouchListener(mOnTouchListener);
        mWindowManager = FloatingManager.getInstance(mContext);
    }

    public void show() {
        mParams = new WindowManager.LayoutParams();
        mParams.gravity = Gravity.TOP | Gravity.LEFT;
        mParams.x = 0;
        mParams.y = 100;
        //总是出现在应用程序窗口之上
        mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //设置图片格式,效果为背景透明
        mParams.format = PixelFormat.RGBA_8888;
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        mParams.width = LayoutParams.WRAP_CONTENT;
        mParams.height = LayoutParams.WRAP_CONTENT;
        mWindowManager.addView(mView, mParams);
        //逐帧动画
        AnimationDrawable animationDrawable=(AnimationDrawable)mImageView.getDrawable();
        animationDrawable.start();
    }

    public void hide() {
        mWindowManager.removeView(mView);
    }

    private OnTouchListener mOnTouchListener = new OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mTouchStartX = (int) event.getRawX();
                    mTouchStartY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    mParams.x += (int) event.getRawX() - mTouchStartX;
                    mParams.y += (int) event.getRawY() - mTouchStartY;//相对于屏幕左上角的位置
                    mWindowManager.updateView(mView, mParams);
                    break;
                case MotionEvent.ACTION_UP:
                    break;
            }
            return true;
        }
    };
}

 

悬浮窗权限

使用mParams.type 值为 WindowManager.LayoutParams.TYPE_PHONE 或 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT 需要申请 android.permission.SYSTEM_ALERT_WINDOW 权限。

  • API >=23,需要在manifest中申请权限,并在每次需要用到权限的时候检查是否已有该权限,因为用户随时可以取消掉。具体可以看
    Android 6.0 运行时权限处理完全解析
    Android M 权限最佳实践
    检测方法:调用系统Settings.canDrawOverlays
  • API >=18,只需要在manifest中申请权限。
    对于一般手机,manifest中声明的权限在安装的时候会默认授权,并不需要处理。
    对于某些rom,需要用AppOpsManager.checkOp方法检测。

因为在API 18,Google新增了一个函数AppOpsManager,不过在这个版本,该函数是隐藏的 (Android 4.3 隐藏功能 App Ops 分析),到API 19才公开。用这个函数可以对manifest申请的权限做一层限制,于是就有了360手机卫士,小米安全中心。。。

检测这些rom的权限,方法是一样的,可以通过反射使用AppOpsManager.checkOp

private static final int OP_SYSTEM_ALERT_WINDOW = 24;

boolean isPermitted = checkOp(context, OP_SYSTEM_ALERT_WINDOW);

private static boolean checkOp(Context context, int op) {
        AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        try {
            Method method = AppOpsManager.class.getDeclaredMethod("checkOp", int.class, int.class, String.class);
            return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
        return false;
    }

判断手机rom

检测应用是否有权限,可以防止异常,或者点击事件没反应。为了给用户提供更好地体验,我们应该引导用户去权限设置页面开启权限。这些特殊rom的权限设置是不一样的,所以需要先判断手机rom,再分别去对应的权限设置页面。

具体方法见:Android判断手机ROM


 

悬浮窗view布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/loading1"/>
</RelativeLayout>

主界面

用两个按钮来控制悬浮窗显示、移除。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mBtnShow;
    private Button mBtnHide;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBtnShow = (Button) findViewById(R.id.btn_show);
        mBtnHide = (Button) findViewById(R.id.btn_hide);

        mBtnShow.setOnClickListener(this);
        mBtnHide.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, MyService.class);
        switch (v.getId()) {
            case R.id.btn_show:
                intent.putExtra(MyService.ACTION, MyService.SHOW);
                break;
            case R.id.btn_hide:
                intent.putExtra(MyService.ACTION, MyService.HIDE);
                break;
        }
        startService(intent);
    }
}

主界面布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="show"/>

    <Button
        android:id="@+id/btn_hide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="hide"/>
</LinearLayout>

使用Service控制悬浮窗

public class MyService extends Service{
    public static final String ACTION="action";
    public static final String SHOW="show";
    public static final String HIDE="hide";
    private FloatingView mFloatingView;

    @Override
    public void onCreate(){
        super.onCreate();
        mFloatingView=new FloatingView(this);
    }

    @Override
    public IBinder onBind(Intent intent){
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String action=intent.getStringExtra(ACTION);
            if(SHOW.equals(action)){
                mFloatingView.show();
            }else if(HIDE.equals(action)){
                mFloatingView.hide();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }
}

service声明

<service android:name=".MyService"/>
資料來源:https://www.jianshu.com/p/881403db1314#

 

相關文章:

https://ddnews.me/tech/ffk20kfq.html

https://ddnews.me/tech/ffk20kfq.html
上面這篇寫的好專業,還有附上測試報告和source code.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *