我已经使用服务的onCreate方法创建了系统覆盖,当我启动服务时,它会按预期创建覆盖。但是,当我尝试从活动中删除此覆盖层并调用服务方法时,总是会给我错误。
这是onCreate服务方法中的代码
wm = getSystemService(Context.WINDOW_SERVICE) as WindowManager
vibrator = this.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
imageView = ImageView(this)
imageView!!.minimumHeight = 30
imageView!!.minimumWidth = 700
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView!!.background = getDrawable(R.drawable.round)
}
imageView!!.setOnClickListener(this)
imageView!!.setOnTouchListener(this)
val params1 = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
layout = LinearLayout(this)
layout!!.layoutParams = params1
layout!!.orientation = LinearLayout.HORIZONTAL
layout!!.gravity = Gravity.CENTER
layout!!.addView(imageView)
val LAYOUT_FLAG: Int
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE
}
val params = WindowManager.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, LAYOUT_FLAG, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT)
params.gravity = Gravity.CENTER or Gravity.BOTTOM
params.x = 0
params.y = 0
wm!!.addView(layout, params)
现在,我正在尝试通过在服务方法中使用以下代码来删除此覆盖,然后从另一个活动中调用此方法
public fun removeBar(){
wm!!.removeView(layout);
}
现在,我在MainActivity中调用以下服务功能
mService = OverlayShowingService();
mService.removeBar()
每当我尝试执行此操作时,都会收到NullPointerException。
W / System.err:kotlin.KotlinNullPointerException