gpt4 book ai didi

java - WindowManager-Bad token exception only on Android 6

转载 作者:行者123 更新时间:2023-11-30 10:48:55 34 4
gpt4 key购买 nike

我有一个扩展服务的类。

public class CustomService extends Service {
private ImageView chatHead;
private WindowManager.LayoutParams params ;
private ImageView iv;

@Override
public void onCreate() {
super.onCreate();
iv = new ImageView(this);
bitmap = BitmapFactory.decodeResource(getResources(), ...);
bitmap = Bitmap.createScaledBitmap(...);
iv.setImageBitmap(bitmap);

//INITIALIZE FROM SCREEN DIMENSIONS
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

//PARAMETERS
params= new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;

params.x = 0;
params.y = mHeight - chatHeadRadius ;

windowManager.addView(iv, params); // HERE WE HAVE THE CRASH
}
}

我以这种方式从我的 mainActivity 创建服务:

        startService(new Intent(getApplication(), MyService.class));

此代码在 Android 4 和 5 的设备上运行得非常好。但是当我尝试在 Marshmallow 上运行它时,我遇到了崩溃。

我必须通知你,我已经尝试过授予权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

在我的 Manifest 文件中,但它没有解决问题。

有什么想法吗?

最佳答案

我终于找到了那个问题的解决方案(在同事的帮助下:)

所以,在我的 MainActivity 中启动服务之前,所有工作都已完成。我必须检查用户是否启用了 Settings.ACTION_MANAGE_OVERLAY_PERMISSION .如果用户没有启用该权限,我将启动一个设置 Activity ,以便用户自己启用该权限。

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, 123);
} else {
// display over lay from service
startService(new Intent(getApplicationContext(), MyService.class));
}
}else
{
// display over lay from service
startService(new Intent(getApplicationContext(), MyService.class));
}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == 123) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.canDrawOverlays(this)) {
// You have permission
// display over lay from service
startService(new Intent(getApplicationContext(), MyService.class));
}
}
}
}

关于java - WindowManager-Bad token exception only on Android 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35603484/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com