1、延迟初始化: lateinit var和by lazy
两者都能够使用的场景下,尽量使用by lazy进行初始化
2、GLSurface截图
//生成GLSurface截图
private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl) {
int[] bitmapBuffer = new int[w * h];
int[] bitmapSource = new int[w * h];
IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
intBuffer.position(0);
try {
gl.glReadPixels(x, y, w, h, 6408, 5121, intBuffer);
for(int i = 0; i < h; ++i) {
int offset1 = i * w;
int offset2 = (h - i - 1) * w;
for(int j = 0; j < w; ++j) {
int texturePixel = bitmapBuffer[offset1 + j];
int blue = texturePixel >> 16 & 255;
int red = texturePixel << 16 & 16711680;
int pixel = texturePixel & -16711936 | red | blue;
bitmapSource[offset2 + j] = pixel;
}
}
} catch (GLException var17) {
return null;
}
return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
}
在onDrawFrame里面
//进入截图
if (isScreenShot) {
isScreenShot = false;
Bitmap screenshot = createBitmapFromGLSurface(0, 0, mOutputWidth, mOutputHeight, gl);
screenshotCallback.getScreenshot(screenshot);
}
在里面可以通过回调的方式将截图传出,在外面通过更改isScreenShot,并调用
Choreographer.getInstance().postFrameCallback(this)
触发OnDrawFrame方法。
3、使用registerForActivityResult请求权限
//请求定位权限的Launcher
private val requestPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (it) {
//用户接受
} else {
val shouldShowRequestPermissionRationale =
ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.ACCESS_FINE_LOCATION
)
if (!shouldShowRequestPermissionRationale) {
//用户拒绝且不再询问
locatePermissionNeverAskAgain()
} else {
//用户拒绝
toastByTry(getString(R.string.refuse_location))
}
}
}