Android實現懸浮窗的簡單方法實例
1. 前言
現在很多應用都有小懸浮窗的功能,比如看直播的時候,通過Home鍵返回桌面,直播的小窗口仍可以在屏幕上顯示。下面將介紹下懸浮窗的的一種簡單實現方式。
2.原理
Window我們應該很熟悉,它是一個接口類,具體的實現類為PhoneWindow,它可以對View進行管理。WindowManager是一個接口類,繼承自ViewManager,從名稱就知道它是用來管理Window的,它的實現類是WindowManagerImpl。如果我們想要對Window(View)進行添加、更新和刪除操作就可以使用WindowManager,WindowManager會將具體的工作交由WindowManagerService處理。這裡我們隻需要知道WindowManager能用來管理Window就好。
WindowManager是一個接口類,繼承自ViewManager,ViewManager中定義瞭3個方法,分佈用來添加、更新和刪除View,如下所示:
public interface ViewManager { public void addView(View view, ViewGroup.LayoutParams params); public void updateViewLayout(View view, ViewGroup.LayoutParams params); public void removeView(View view); }
WindowManager也繼承瞭這些方法,而這些方法傳入的參數都是View類型,說明瞭Window是以View的形式存在的。
3.具體實現
3.1浮窗佈局
懸浮窗的簡易佈局如下的可參考下面的layout_floating_window.xml文件。頂層深色部分的FrameLayout佈局是用來實現懸浮窗的拖拽功能的,點擊右上角ImageView可以實現關閉懸浮窗,剩下區域顯示內容,這裡隻是簡單地顯示文本內容,不做復雜的東西,故隻設置TextView。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <FrameLayout android:id="@+id/layout_drag" android:layout_width="match_parent" android:layout_height="15dp" android:background="#dddddd"> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/iv_close" android:layout_width="15dp" android:layout_height="15dp" android:layout_gravity="end" android:src="@drawable/img_delete"/> </FrameLayout> <androidx.appcompat.widget.AppCompatTextView android:id="@+id/tv_content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center_horizontal" android:background="#eeeeee" android:scrollbars="vertical"/> </LinearLayout>
3.2 懸浮窗的實現
1. 使用服務Service
Service 是一種可在後臺執行長時間運行操作而不提供界面的應用組件,可由其他應用組件啟動,而且即使用戶切換到其他應用,仍將在後臺繼續運行。要保證應用在後臺時,懸浮窗仍然可以正常顯示,所以這裡可以使用Service。
2. 獲取WindowManager並設置LayoutParams
private lateinit var windowManager: WindowManager private lateinit var layoutParams: WindowManager.LayoutParams override fun onCreate() { // 獲取WindowManager 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 // 設置浮窗的大小和位置 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 } }
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, startId: Int): Int { if (Settings.canDrawOverlays(this)) { floatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_window.xml, null) windowManager.addView(floatingView, layoutParams) // 點擊浮窗的右上角關閉按鈕可以關閉浮窗 floatingView.findViewById<AppCompatImageView>(R.id.iv_close).setOnClickListener { windowManager.removeView(floatingView) } // 實現浮窗的拖動功能, 通過改變layoutParams來實現 floatingView.findViewById<AppCompatImageView>(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中添加:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
此外,還要通過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<AppCompatImageView>(R.id.iv_close).setOnClickListener { stringBuilder.clear() windowManager.removeView(floatingView) attached = false } // 設置TextView滾動 tvContent.movementMethod = ScrollingMovementMethod.getInstance() floatingView!!.findViewById<FrameLayout>(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 windowManager.updateViewLayout(floatingView, layoutParams) } } true } windowManager.addView(floatingView, layoutParams) attached = true } return super.onStartCommand(intent, flags, startId) } override fun onDestroy() { // 註銷廣播並刪除浮窗 unregisterReceiver(receiver) receiver = null if (attached) { windowManager.removeView(floatingView) } } inner class MyReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val content = intent.getStringExtra("content") ?: "" stringBuilder.append(content).append("\n") val message = Message.obtain() message.what = 0 message.obj = stringBuilder.toString() handler.sendMessage(message) } } }
4. 總結
以上就是Android懸浮窗的一個簡單實現方式。如果需要實現其他復雜一點的功能,比如播放視頻,也可以在此基礎上完成。
到此這篇關於Android實現懸浮窗的簡單方法的文章就介紹到這瞭,更多相關Android實現懸浮窗內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Android仿騰訊視頻實現懸浮窗效果
- Android創建懸浮窗的完整步驟
- Android實現圓形菜單懸浮窗
- Android應用內懸浮窗Activity的簡單實現
- Android仿IOS系統懸浮窗效果