androidandroid-studioandroid-gradle-plugin

Suspicious cast to text for a CLIPBOARD_SERVICE: expected ClipboardManager [ServiceCast]


When building a release version of my app the build fails with the following error:

Error:Error: Suspicious cast to text for a CLIPBOARD_SERVICE: expected ClipboardManager [ServiceCast]

Debug version builds fine.

If I comment out the pre SDK 11 code below it builds fine.

How can I solve this error?

Code:

@TargetApi(11)
@SuppressWarnings("deprecation")
public void btnCopyClicked(View button) {
    if (Build.VERSION.SDK_INT < 11) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(aString);
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData.newPlainText("aString", aString);
        clipboard.setPrimaryClip(clip);
    }
}

Environment:

Project build.gradle:

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'io.fabric.tools:gradle:1.22.1'
    }
    ...
}

App build.gradle:

android {
    compileSdkVersion 'Google Inc.:Google APIs:21'
    buildToolsVersion '25.0.0'
    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 21
        ...
    }
    ...
}

Solution

  • It seems to be a bug in ServiceCastDetector in lint. To workaround convert the following code

    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(aString);
    

    to

    Object clipboard = getSystemService(Context.CLIPBOARD_SERVICE);
    ((android.text.ClipboardManager)clipboard).setText(aString);