要实现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);
这样就可以实现一个简单的Android悬浮窗功能了。当然,实际应用中可能还需要添加一些其他功能,比如拖动悬浮窗、点击事件处理等。