I was trying to use Android Support RenderScript to make blur effect with bitmaps, but when testing on some devices (API 22) my app crashes with "two contexts with different SDK versions" error.
It was very strange that nobody has asked this before!
build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
minSdkVersion 16
targetSdkVersion 23
versionCode 1
renderscriptTargetApi 18
renderscriptSupportModeEnabled true
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:support-vector-drawable:23.2.1'
compile 'com.android.support:support-annotations:23.2.1'
compile 'com.android.support:support-v13:23.2.1'
compile 'com.android.support:support-v4:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:palette-v7:23.2.1'
compile 'com.android.support:recyclerview-v7:23.2.1'
compile 'com.android.support:cardview-v7:23.2.1'
MainActivity.java
public Bitmap blurImage(Bitmap image) {
final float BITMAP_SCALE = 0.4f;
final float BLUR_RADIUS = 7.5f;
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
It crashes when trying to do this:
RenderScript rs = RenderScript.create(context);
The function and the bitmap are both in the same activity, my question is: What is causing two different contexts?
Check your imports. You're most likely importing android.renderscript.RenderScript
in one file and android.support.v8.renderscript.RenderScript
in the other one. The context is tied to your app context, so there can only be one or the other in your application.
On a related note, if the above method is exactly the same between the two files I would suggest making a utility helper class so your code is only in one place.