安卓8.0之后的悬浮窗demo
时间: 2023-11-21 16:03:56 浏览: 30
好的,您可以参考下面的代码实现:
1. 在 AndroidManifest.xml 文件中添加悬浮窗权限:
```xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
```
2. 创建一个悬浮窗 Service:
```java
public class FloatWindowService extends Service {
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutParams;
private View mFloatView;
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mLayoutParams.format = PixelFormat.RGBA_8888;
mLayoutParams.gravity = Gravity.START | Gravity.TOP;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
// 创建悬浮窗视图
mFloatView = LayoutInflater.from(this).inflate(R.layout.float_window, null);
// 设置悬浮窗视图的点击事件
mFloatView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 点击悬浮窗执行的操作
}
});
// 将悬浮窗视图添加到窗口
mWindowManager.addView(mFloatView, mLayoutParams);
}
@Override
public void onDestroy() {
super.onDestroy();
// 销毁悬浮窗视图
mWindowManager.removeView(mFloatView);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
```
3. 创建一个悬浮窗布局文件 float_window.xml:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/float_window_icon"/>
</RelativeLayout>
```
4. 在需要显示悬浮窗的地方启动 FloatWindowService:
```java
Intent intent = new Intent(this, FloatWindowService.class);
startService(intent);
```
以上就是一个简单的悬浮窗实现方法,您可以根据自己的需求进行修改和扩展。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)