Skip to content

Instantly share code, notes, and snippets.

@skyisle
Created May 2, 2013 06:07
Show Gist options
  • Save skyisle/5500427 to your computer and use it in GitHub Desktop.
Save skyisle/5500427 to your computer and use it in GitHub Desktop.
Adsense Android 4.0.3+ devicemotion crash workaround
class WebViewClientEx extends WebViewClient {
private static final String URL_ADSENSE_SHOW_ADS_JS
= "pagead2.googlesyndication.com/pagead/show_ads.js";
public android.webkit.WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (Build.VERSION.SDK_INT >= 15
&& url.endsWith(URL_ADSENSE_SHOW_ADS_JS)) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
String devicemotionWorkaround
= "window.DeviceMotionEvent = undefined;\nconsole.log('Adsense Android 4.0.3+ devicemotion crash workaround activated');\n";
final ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(devicemotionWorkaround.getBytes());
final byte[] buffer = new byte[8192];
int read;
while ((read = in.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
return new android.webkit.WebResourceResponse("text/javascript", "UTF-8",
new ByteArrayInputStream(output.toByteArray()));
} catch (MalformedURLException e) {
log.error("shouldInterceptRequest error", e);
} catch (IOException e) {
log.error("shouldInterceptRequest error", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment