最近公司的录屏项目需要的一个功能,有一个悬浮窗功能,点击悬浮窗按钮就能直接录屏,需求很简单,但是遇到一个很蛋疼的问题,就是请求android的录屏权限必须要是使用startActivityForResult,如果直接在桌面请求会有一个问题,那就是悬浮窗在桌面时,点击悬浮窗会后台唤起app,这就很不友好了,在网上查阅了各种资料也无果,最后终于想到了一个方法,自己新建一个申请权限的activity,并把它的主题设置为透明,然而还是不行,最后又一波百度谷歌,给activity加了一个单例的启动模式后终于成功,我主要贴出了PermissionActivity的代码,后面有github的完整代码。
Manifest清单文件
<activity android:name=".activity.PermissionActivity"
android:launchMode="singleInstance"
android:theme="@style/NoActivity">
</activity>
PermissionActivity
class PermissionActivity : Activity() {
private var projectionManager: MediaProjectionManager? = null
/** 屏幕录制控制 */
private var mRecordService: RecordService.RecordBinder? = null
/** 服务绑定回调 */
private var mServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
mRecordService = null
Log.d("record","服务解绑")
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
mRecordService = service as RecordService.RecordBinder
Log.d("record","服务绑定")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
projectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
val intent = Intent(this, RecordService::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
val captureIntent = projectionManager?.createScreenCaptureIntent()
startActivityForResult(captureIntent, RECORD_REQUEST_CODE)
}
override fun onDestroy() {
super.onDestroy()
unbindService(mServiceConnection)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
mRecordService?.onRequestResult(requestCode, resultCode, data)
finish()
}
}
透明主题
<style name="NoActivity" parent="android:Theme.Translucent.NoTitleBar.Fullscreen">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
https://github.com/song234876/ScreenDemo
网友评论