要實現(xiàn)Android懸浮窗,可以按照以下步驟進行編寫代碼:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
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);
}
}
}
<?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>
Intent intent = new Intent(this, FloatWindowService.class);
startService(intent);
這樣就可以實現(xiàn)一個簡單的Android懸浮窗功能了。當然,實際應(yīng)用中可能還需要添加一些其他功能,比如拖動懸浮窗、點擊事件處理等。