溫馨提示×

android懸浮窗實現(xiàn)代碼怎么寫

小億
201
2024-06-04 10:51:26
欄目: 編程語言

要實現(xiàn)Android懸浮窗,可以按照以下步驟進行編寫代碼:

  1. 在AndroidManifest.xml文件中添加懸浮窗權(quán)限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
  1. 創(chuàng)建一個Service類來實現(xiàn)懸浮窗功能,例如FloatWindowService:
public class FloatWindowService extends Service {

    private WindowManager mWindowManager;
    private View mFloatView;

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

    @Override
    public void onCreate() {
        super.onCreate();
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mFloatView = LayoutInflater.from(this).inflate(R.layout.layout_float_window, null);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );
        params.gravity = Gravity.LEFT | Gravity.TOP;
        params.x = 0;
        params.y = 0;
        mWindowManager.addView(mFloatView, params);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWindowManager != null && mFloatView != null) {
            mWindowManager.removeView(mFloatView);
        }
    }
}
  1. 在res/layout文件夾下創(chuàng)建一個布局文件layout_float_window.xml,用于定義懸浮窗的布局,例如:
<?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:background="@android:color/transparent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Floating Window"
        android:textSize="16sp"
        android:textColor="@android:color/black" />

</LinearLayout>
  1. 在MainActivity中啟動FloatWindowService:
Intent intent = new Intent(this, FloatWindowService.class);
startService(intent);

這樣就可以實現(xiàn)一個簡單的Android懸浮窗功能了。當然,實際應(yīng)用中可能還需要添加一些其他功能,比如拖動懸浮窗、點擊事件處理等。

0