Android懸浮框的實現

DeMonnnnnn發表於2018-08-13

前言

懸浮框常用於手機助手,應用內全域性控制等場景。
今天就來介紹如何實現懸浮框。

思路

  1. 使用WindowManager可以在螢幕上新增自定義view。
  2. Android api 23以上需要申請懸浮窗許可權。
  3. 由於懸浮框不受Activity影響,甚至程式關閉仍能存在,所以懸浮框執行在Service中。
  4. 將懸浮框與Serivce的生命週期繫結就可以通過stopService可以關閉懸浮框。

Android懸浮框的實現Android懸浮框的實現

實現

具體實現不難,請看程式碼。

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>

原始碼

https://github.com/Demo-DeMon/SuspensionBox

相關文章