Android悬浮窗的简单实现,移动app软件开发工程师就业前景

}

}

3. 创建View并添加到WindowManager

private lateinit var floatingView: View

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

if (Settings.canDrawOverlays(this)) {

floatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_window.xml, null)

windowManager.addView(floatingView, layoutParams)

}

return super.onStartCommand(intent, flags, startId)

}

4. 实现悬浮窗的拖拽和关闭功能

// 浮窗的坐标

private var x = 0

private var y = 0

override fun onStartCommand(intent: Intent?, flags: Int, sta
rtId: Int): Int {

if (Settings.canDrawOverlays(this)) {

floatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_window.xml, null)

windowManager.addView(floatingView, layoutParams)

// 点击浮窗的右上角关闭按钮可以关闭浮窗

floatingView.findViewById(R.id.iv_close).setOnClickListener {

windowManager.removeView(floatingView)

}

// 实现浮窗的拖动功能, 通过改变layoutParams来实现

floatingView.findViewById(R.id.layout_drag).setOnTouchListener { v, event ->

when (event.action) {

MotionEvent.ACTION_DOWN -> {

x = event.rawX.toInt()

y = event.rawY.toInt()

}

MotionEvent.ACTION_MOVE -> {

val currentX = event.rawX.toInt()

val currentY = event.rawY.toInt()

val offsetX = currentX - x

val offsetY = currentY - y

x = currentX

y = currentY

layoutParams.x = layoutParams.x + offsetX

layoutParams.y = layoutParams.y + offsetY

// 更新floatingView

windowManager.updateViewLayout(floatingView, layoutParams)

}

}

true

}

return super.onStartCommand(intent, flags, startId)

}

5. 利用广播进行通信

private var receiver: MyReceiver? = null

override fun onCreate() {

// 注册广播

receiver = MyReceiver()

val filter = IntentFilter()

filter.addAction(“android.intent.action.MyReceiver”)

registerReceiver(receiver, filter)

}

inner class MyReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {

val content = intent.getStringExtra(“content”) ?: “”

// 通过Handler更新UI

val message = Message.obtain()

message.what = 0

message.obj = content

handler.sendMessage(message)

}

}

val handler = Handler(this.mainLooper) { msg ->

tvContent.text = msg.obj as String

false

}

可以在Activity中通过广播给Service发送信息

fun sendMessage(view: View?) {

Intent(“android.intent.action.MyReceiver”).apply {

putExtra(“content”, “Hello, World!”)

sendBroadcast(this)

}

}

6. 设置权限

悬浮窗的显示需要权限,在AndroidManefest.xml中添加:

此外,还要通过Settings.ACTION_MANAGE_OVERLAY_PERMISSION来让动态设置权限,在Activity中设置。

// MainActivity.kt

fun startWindow(view: View?) {

if (!Settings.canDrawOverlays(this)) {

startActivityForResult(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse(“package:$packageName”)), 0)

} else {

startService(Intent(this@MainActivity, FloatingWindowService::class.java))

}

}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

super.onActivityResult(requestCode, resultCode, data)

if (requestCode == 0) {

if (Settings.canDrawOverlays(this)) {

Toast.makeText(this, “悬浮窗权限授权成功”, Toast.LENGTH_SHORT).show()

startService(Intent(this@MainActivity, FloatingWindowService::class.java))

}

}

}

3.3 完整代码

class FloatingWindowService : Service() {

private lateinit var windowManager: WindowManager

private lateinit var layoutParams: WindowManager.LayoutParams

private lateinit var tvContent: AppCompatTextView

private lateinit var handler: Handler

private var receiver: MyReceiver? = null

private var floatingView: View? = null

private val stringBuilder = StringBuilder()

private var x = 0

private var y = 0

// 用来判断floatingView是否attached 到 window manager,防止二次removeView导致崩溃

private var attached = false

override fun onCreate() {

super.onCreate()

// 注册广播

receiver = MyReceiver()

val filter = IntentFilter()

filter.addAction(“android.intent.action.MyReceiver”)

registerReceiver(receiver, filter);

// 获取windowManager并设置layoutParams

windowManager = getSystemService(WINDOW_SERVICE) as WindowManager

layoutParams = WindowManager.LayoutParams().apply {

type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY

} else {

WindowManager.LayoutParams.TYPE_PHONE

}

format = PixelFormat.RGBA_8888

// format = PixelFormat.TRANSPARENT

gravity = Gravity.START or Gravity.TOP

flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE

width = 600

height = 600

x = 300

y = 300

}

handler = Handler(this.mainLooper) { msg ->

tvContent.text = msg.obj as String

// 当文本超出屏幕自动滚动,保证文本处于最底部

val offset = tvContent.lineCount * tvContent.lineHeight

floatingView?.apply {

if (offset > height) {

tvContent.scrollTo(0, offset - height)

}

}

false

}

}

override fun onBind(intent: Intent?): IBinder? {

return null

}

@SuppressLint(“ClickableViewAccessibility”)

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

if (Settings.canDrawOverlays(this)) {

floatingView = LayoutInflater.from(this).inflate(R.layout.layout_show_log, null)

tvContent = floatingView!!.findViewById(R.id.tv_log)

floatingView!!.findViewById(R.id.iv_close).setOnClickListener {

stringBuilder.clear()

windowManager.removeView(floatingView)

attached = false

}

// 设置TextView滚动

tvContent.movementMethod = ScrollingMovementMethod.getInstance()
{

floatingView = LayoutInflater.from(this).inflate(R.layout.layout_show_log, null)

tvContent = floatingView!!.findViewById(R.id.tv_log)

floatingView!!.findViewById(R.id.iv_close).setOnClickListener {

stringBuilder.clear()

windowManager.removeView(floatingView)

attached = false

}

// 设置TextView滚动

tvContent.movementMethod = ScrollingMovementMethod.getInstance()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于 Android 浮窗广告的实现,需要用到 AndroidWindowManager 类,下面是一个简单实现方式: 1. 在 AndroidManifest.xml 文件中添加权限: ``` <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> ``` 2. 创建一个悬浮窗的布局文件,例如 float_window.xml: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/float_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:orientation="vertical"> <!-- 在这里添加你的广告布局 --> </LinearLayout> ``` 3. 创建一个 Service 类用于控制悬浮窗的显示和隐藏: ```java public class FloatWindowService extends Service { private WindowManager windowManager; private LinearLayout floatLayout; private WindowManager.LayoutParams params; @Override public void onCreate() { super.onCreate(); windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); // 设置悬浮窗的布局参数 params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); // 设置悬浮窗的位置 params.gravity = Gravity.TOP | Gravity.LEFT; params.x = 0; params.y = 0; // 加载悬浮窗的布局文件 LayoutInflater inflater = LayoutInflater.from(this); floatLayout = (LinearLayout) inflater.inflate(R.layout.float_window, null); // 在这里添加你的广告布局 // 将悬浮窗添加到 WindowManagerwindowManager.addView(floatLayout, params); } @Override public void onDestroy() { super.onDestroy(); // 在 Service 销毁时移除悬浮窗 if (floatLayout != null) { windowManager.removeView(floatLayout); } } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } ``` 4. 在需要显示悬浮窗的地方启动 Service: ```java startService(new Intent(this, FloatWindowService.class)); ``` 这样就可以实现一个简单Android 浮窗广告了。当然,你也可以根据自己的需求对悬浮窗进行更加复杂的实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值