我正在使用服务来创建一个facebook messenger样式的chatHead。我的代码适用于Android OS至6(Marshmallow)的设备。但是在M设备上,代码在windowManager.addView()
上崩溃并出现运行时异常代码如下:
windowManager = (WindowManager) ctx.getSystemService(WINDOW_SERVICE);
callHead = new ImageView(this);
callHead.setImageResource(R.drawable.ic_flow_flat);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
PixelFormat.TRANSLUCENT);
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
| WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
params.height = 120; // given it a fixed height in case of large image
params.width = 120;
windowManager.addView(callHead, params);
我收到的崩溃是
Caused by: android.view.WindowManager$InvalidDisplayException: Unable to add window android.view.ViewRootImpl$W@b40f577 -- the specified window type is not valid
答案 0 :(得分:3)
看了http://qiita.com/chibatching/items/add5e50921c2da5ee1c7然后自己尝试
检查您的代码是否在Marshmallow及以上版本上运行。如果是,请检查应用是否具有绘制叠加层的权限。如果没有指导用户进行设置。在onActivityResult中,如果用户已授予权限,则可以调用displayOverdraw。如果用户先前已授予权限,则无需再次显示设置屏幕。
public void checkdrawPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, REQUEST_CODE_ASK_PERMISSIONS);
} else {
// display over lay from service
}
}else
{
// display over lay from service
}
}
onActivityResult回调
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_ASK_PERMISSIONS) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.canDrawOverlays(this)) {
// You have permission
// display over lay from service
}
}
}
}
服务中的绘图叠加层
public void displayOverdraw() {
ImageView callHead = new ImageView(this);
callHead.setImageResource(R.mipmap.ic_launcher);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(callHead, params);
}
注意:为了测试我在活动中试过这个。在服务中,您无法调用startActivityForResult