[ERROR] [1490584542.510624]: bad callback: <boundcall methodd Detector.image_callback of <__main__.Dete

Create account
Be part of the largest Android community
Continue with Google
Continue with Facebook
Stay signed in
Already registered?
First of all, I would like to thank you in advance for taking your time and reading this.
I have an app that loads a webpage in a webview where the user can upload a file by taking a picture.
It works pretty well on all (real) devices that I tested, except with the Moto G3.
When I take more than one picture, the app goes black and restarts, taking the user again to the login page that I have prior to the upload picture page.
The console gives me this line of error: E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
First, I?m trying to understand why I?m getting this behavior (I suspect it is a memory related issue) and after that treat the error so that if this happens again I can send a toast or an alert to the user instead of letting the app crash and make the user login again.
Here is the code:
public class MainActivity extends AppCompatActivity {
PermissoesUtil permissoesU
private WebView webV
private static final String TAG = MainActivity.class.getSimpleName();
private void setWebView(){
webView = (WebView) findViewById(R.id.activity_main_webview);
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
if (grantResults.length & 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(view,"Permissao autorizada",Snackbar.LENGTH_LONG).show();
Snackbar.make(view,"Permissao negada",Snackbar.LENGTH_LONG).show();
public void destroiDadosWebView(WebView webView){
Log.i(TAG, "Destruindo os dados do webview - inicio");
if (webView == null){
webView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = webView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);
webSettings.setJavaScriptEnabled(false);
webSettings.setDatabaseEnabled(false);
webSettings.setAllowFileAccess(false);
webSettings.setDomStorageEnabled(false);
webSettings.setAllowFileAccess(false);
webSettings.setLoadWithOverviewMode(false);
webSettings.setUseWideViewPort(false);
webSettings.setSupportZoom(false);
webSettings.setCacheMode(0);
webSettings.setDatabaseEnabled(false);
webSettings.setSaveFormData(false);
Map&String, String& noCacheHeaders = new HashMap&String, String&(2);
noCacheHeaders.put("Pragma", "no-cache");
noCacheHeaders.put("Cache-Control", "no-cache");
noCacheHeaders.put("Accept-Language", Locale.getDefault().toString());
webView.loadUrl("urlRemovedCantPutLinksInHere", noCacheHeaders);
webView.clearFormData();
webView.clearHistory();
webView.clearMatches();
webView.removeAllViews();
webView.clearCache(true);
webView.destroyDrawingCache();
this.unregisterForContextMenu(webView);
webView.removeAllViews();
if (Build.VERSION.SDK_INT &= Build.VERSION_CODES.JELLY_BEAN_MR2) { //para tratar o crash do aplicativo no comando em vers?es antigas
webView.destroy();
Log.i(TAG, "Destruindo os dados do webview - fim");
Log.i(TAG, "Destruindo os cookies do webview - inicio");
CookieManager cookieManager = CookieManager.getInstance();
Context context = webView.getContext();
if (Build.VERSION.SDK_INT &= Build.VERSION_CODES.LOLLIPOP_MR1) {
Log.i(TAG, "Destruindo cookies &=" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
Log.i(TAG, "Destruindo cookies &" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
cookieSyncMngr.startSync();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
Log.i(TAG, "Destruindo os cookies do webview - fim");
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.i(TAG, "[:EBUG::] Come?ando o aplicativo....");
permissoesUtil = new PermissoesUtil();
boolean temPermissaoTelaAtiva = permissoesUtil.verificaPermissao(getApplicationContext(), Manifest.permission.WAKE_LOCK);
if (Build.VERSION.SDK_INT &= Build.VERSION_CODES.M) {
// se for android v6 ou superior verificar cada uma das permiss?es e solicitar caso esteja faltando
boolean temPermissaoGPS = permissoesUtil.verificaPermissao(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
boolean temPermissaoArquivos = permissoesUtil.verificaPermissao(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
boolean temPermissaoTelefone = permissoesUtil.verificaPermissao(getApplicationContext(), Manifest.permission.READ_PHONE_STATE);
if ((!temPermissaoGPS)|| (!temPermissaoArquivos) || (!temPermissaoTelefone) || (!temPermissaoTelaAtiva)){ //caso n?o tenha uma das permiss?es vai solicitar todas
permissoesUtil.getPermissoes(this);
if (!temPermissaoTelaAtiva){
permissoesUtil.getPermissoes(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // deixa a tela acessa durante a execu??o da atividade principal do app
setWebView(); //aponta o webView correto para carregar o website
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //descomentar esta linha para aplicativos no modo paisagem
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); // desabilita a rota??o da tela
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); // habilita a rota??o da tela
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.w("Escuta da rede", "Tipo de conex?o alterada");
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Snackbar.make(findViewById(android.R.id.content), "Dispositivo sem conectividade", Snackbar.LENGTH_LONG).setAction("Action", null).show();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkStateReceiver, filter);
String url_aplicacao = getResources().getString(R.string.url_aplicacao);
initWebView(webView);
webView.loadUrl(url_aplicacao);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.hide();
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Snackbar.make(view, "Enviar os dados para a central", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
//inicio exemplo web
private final static Object methodInvoke(Object obj, String method, Class&?&[] parameterTypes, Object[] args) {
Method m = obj.getClass().getMethod(method, new Class[] { boolean.class });
m.invoke(obj, args);
} catch (Exception e) {
e.printStackTrace();
private void initWebView(WebView webView) {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
String databasePath = this.getApplicationContext().getDir("database",Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
File dir = getCacheDir();
if (!dir.exists()) {
dir.mkdirs();
settings.setAllowFileAccess(true);
settings.setDomStorageEnabled(true);
settings.setAppCachePath(String.valueOf(getApplicationContext()));
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setAppCacheEnabled(true);
settings.setAllowFileAccess(true);
settings.setDatabaseEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// settings.setPluginsEnabled(true);
methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
// settings.setPluginState(PluginState.ON);
methodInvoke(settings, "setPluginState", new Class[] { WebSettings.PluginState.class }, new Object[] { WebSettings.PluginState.ON });
// settings.setPluginsEnabled(true);
methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
// settings.setAllowUniversalAccessFromFileURLs(true);
methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
// settings.setAllowFileAccessFromFileURLs(true);
methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//webView.clearHistory();
//webView.clearFormData();
//webView.clearCache(true);
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request( Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "MANUAL_DO_SISTEMA.pdf");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Gravando o arquivo no dispositivo", Toast.LENGTH_LONG).show();
webView.setWebViewClient(new WebViewClient() {@Override
public void onLoadResource(WebView view, String url) {
System.out.println("URL = " + url + " " + Html.fromHtml("&br&") + " http =
" + URLUtil.isHttpUrl(url));
}@Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
URL url1 =
url1 = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(TAG, "String url = " + url);
Log.i(TAG, "getRef = " + url1.getRef());
Log.i(TAG, "getHost = " + url1.getHost());
Log.i(TAG, "getAuthority = " + url1.getAuthority());
String cookies = CookieManager.getInstance().getCookie(url);
Log.i(TAG, "Cookies = " + cookies);
//Toast.makeText(getApplicationContext(), "All Cookies " + cookies, Toast.LENGTH_LONG).show();
webView.setWebChromeClient(new MyWebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
UploadHandler mUploadH
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == Controller.FILE_SELECTED) {
// Chose a file from the file picker.
if (mUploadHandler != null) {
mUploadHandler.onResult(resultCode, intent);
super.onActivityResult(requestCode, resultCode, intent);
class MyWebChromeClient extends WebChromeClient {
public MyWebChromeClient() {
private String getTitleFromUrl(String url) {
URL urlObj = new URL(url);
String host = urlObj.getHost();
if (host != null && !host.isEmpty()) {
return urlObj.getProtocol() + "://" +
if (url.startsWith("file:")) {
String fileName = urlObj.getFile();
if (fileName != null && !fileName.isEmpty()) {
return fileN
} catch (Exception e) {
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
String newTitle = getTitleFromUrl(url);
new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}).setCancelable(false).create().show();
// return super.onJsAlert(view, url, message, result);
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
String newTitle = getTitleFromUrl(url);
new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}).setCancelable(false).create().show();
// return super.onJsConfirm(view, url, message, result);
// Android 4.1
public void openFileChooser(ValueCallback&Uri& uploadMsg, String acceptType, String capture) {
Log.i(TAG, "[:EBUG::] Chooser 4.1....");
mUploadHandler = new UploadHandler(new Controller());
mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
// Android 4.4, 4.4.1, 4.4.2
// openFileChooser function is not called on Android 4.4, 4.4.1, 4.4.2,
// you may use your own java script interface or other hybrid framework.
// Android 5.0.1
public boolean onShowFileChooser(
WebView webView, ValueCallback&Uri[]& filePathCallback,
FileChooserParams fileChooserParams) {
Log.i(TAG, "[:EBUG::] Chooser 5.0.1....");
String acceptTypes[] = fileChooserParams.getAcceptTypes();
String acceptType = "";
for (int i = 0; i & acceptTypes. ++ i) {
if (acceptTypes[i] != null && acceptTypes[i].length() != 0)
acceptType += acceptTypes[i] + ";";
if (acceptType.length() == 0)
acceptType = "*/*";
final ValueCallback&Uri[]& finalFilePathCallback = filePathC
ValueCallback&Uri& vc = new ValueCallback&Uri&() {
public void onReceiveValue(Uri value) {
if (value != null)
result = new Uri[]{value};
finalFilePathCallback.onReceiveValue(result);
//openFileChooser(vc, acceptType, "filesystem");
openFileChooser(vc, acceptType, "camera");
class Controller {
final static int FILE_SELECTED = 4;
Activity getActivity() {
return MainActivity.
// copied from android-4.4.3_r1/src/com/android/browser/UploadHandler.java
//////////////////////////////////////////////////////////////////////
* Copyright (C) 2010 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
class UploadHandler {
* The Object used to inform the WebView of the file to upload.
private ValueCallback&Uri& mUploadM
private String mCameraFileP
private boolean mH
private boolean mCaughtActivityNotFoundE
private Controller mC
public UploadHandler(Controller controller) {
mController =
String getFilePath() {
return mCameraFileP
boolean handled() {
void onResult(int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
// Couldn't resolve an activity, we are going to try again so skip
// this result.
mCaughtActivityNotFoundException =
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
: intent.getData();
// As we ask the camera to save the result of the user taking
// a picture, the camera application does not return anything other
// than RESULT_OK. So we need to check whether the file we expected
// was written to disk in the in the case that we
// did not get an intent returned but did get a RESULT_OK. If it was,
// we assume that this result has came back from the camera.
if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
File cameraFile = new File(mCameraFilePath);
if (cameraFile.exists()) {
result = Uri.fromFile(cameraFile);
// Broadcast to the media scanner that we have a new photo
// so it will be added into the gallery for the user.
mController.getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
mUploadMessage.onReceiveValue(result);
mHandled =
mCaughtActivityNotFoundException =
void openFileChooser(ValueCallback&Uri& uploadMsg, String acceptType, String capture) {
final String imageMimeType = "image/*";
final String videoMimeType = "video/*";
final String audioMimeType = "audio/*";
final String mediaSourceKey = "capture";
final String mediaSourceValueCamera = "camera";
final String mediaSourceValueFileSystem = "filesystem";
final String mediaSourceValueCamcorder = "camcorder";
final String mediaSourceValueMicrophone = "microphone";
// TESTE EGL
// FIM TESTE EGL
// According to the spec, media source can be 'filesystem' or 'camera' or 'camcorder'
// or 'microphone' and the default value should be 'filesystem'.
String mediaSource = mediaSourceValueFileS
if (mUploadMessage != null) {
// Already a file picker operation in progress.
mUploadMessage = uploadM
// Parse the accept type.
String params[] = acceptType.split(";");
String mimeType = params[0];
if (capture.length() & 0) {
mediaSource =
if (capture.equals(mediaSourceValueFileSystem)) {
Log.i(TAG, "[:EBUG::] Capturando o valor da submiss?o de arquivo....");
// To maintain backwards compatibility with the previous implementation
// of the media capture API, if the value of the 'capture' attribute is
// "filesystem", we should examine the accept-type for a MIME type that
// may specify a different capture value.
for (String p : params) {
String[] keyValue = p.split("=");
if (keyValue.length == 2) {
// Process key=value parameters.
if (mediaSourceKey.equals(keyValue[0])) {
mediaSource = keyValue[1];
//Ensure it is not still set from a previous upload.
mCameraFilePath =
if (mimeType.equals(imageMimeType)) {
Log.i(TAG, "[:EBUG::] Recebendo uma imagem....");
if (mediaSource.equals(mediaSourceValueCamera)) {
// Specified 'image/*' and requested the camera, so go ahead and launch the
// camera directly.
startActivity(createCameraIntent());
// Specified just 'image/*', capture=filesystem, or an invalid capture parameter.
// In all these cases we show a traditional picker filetered on accept type
// so launch an intent for both the Camera and image/* OPENABLE.
Intent chooser = createChooserIntent(createCameraIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
startActivity(chooser);
} else if (mimeType.equals(videoMimeType)) {
if (mediaSource.equals(mediaSourceValueCamcorder)) {
// Specified 'video/*' and requested the camcorder, so go ahead and launch the
// camcorder directly.
startActivity(createCamcorderIntent());
// Specified just 'video/*', capture=filesystem or an invalid capture parameter.
// In all these cases we show an intent for the traditional file picker, filtered
// on accept type so launch an intent for both camcorder and video/* OPENABLE.
Intent chooser = createChooserIntent(createCamcorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
startActivity(chooser);
} else if (mimeType.equals(audioMimeType)) {
if (mediaSource.equals(mediaSourceValueMicrophone)) {
// Specified 'audio/*' and requested microphone, so go ahead and launch the sound
// recorder.
startActivity(createSoundRecorderIntent());
// Specified just 'audio/*',
capture=filesystem of an invalid capture parameter.
// In all these cases so go ahead and launch an intent for both the sound
// recorder and audio/* OPENABLE.
Intent chooser = createChooserIntent(createSoundRecorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
startActivity(chooser);
// No special handling based on the accept type was necessary, so trigger the default
// file upload chooser.
startActivity(createDefaultOpenableIntent());
private void startActivity(Intent intent) {
mController.getActivity().startActivityForResult(intent, Controller.FILE_SELECTED);
} catch (ActivityNotFoundException e) {
// No installed app was able to handle the intent that
// we sent, so fallback to the default file upload control.
mCaughtActivityNotFoundException =
mController.getActivity().startActivityForResult(createDefaultOpenableIntent(),
Controller.FILE_SELECTED);
} catch (ActivityNotFoundException e2) {
// Nothing can return us a file, so file upload is effectively disabled.
Toast.makeText(mController.getActivity(), R.string.uploads_disabled,
Toast.LENGTH_LONG).show();
private Intent createDefaultOpenableIntent() {
// Create and return a chooser with the default OPENABLE
// actions including the camera, camcorder and sound
// recorder where available.
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),
createSoundRecorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, i);
private Intent createChooserIntent(Intent... intents) {
Log.i(TAG, "[:EBUG::] Intent do chooser....");
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
chooser.putExtra(Intent.EXTRA_TITLE, mController.getActivity().getResources()
.getString(R.string.choose_upload));
private Intent createOpenableIntent(String type) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(type);
private Intent createCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File externalDataDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM);
File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
File.separator + "browser-photos");
cameraDataDir.mkdirs();
mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
System.currentTimeMillis() + ".jpg";
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
Log.i(TAG, "[:EBUG::] Realizando o intent da camera....");
return cameraI
private Intent createCamcorderIntent() {
return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
private Intent createSoundRecorderIntent() {
return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
//termino exemplo web
public boolean onCreateOptionsMenu(Menu menu) {
// I this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_configuracoes) {
Intent intent = new Intent(MainActivity.this, VerificaConfiguracoes.class);
startActivity(intent);
return super.onOptionsItemSelected(item);

我要回帖

更多关于 bound method 错误 的文章

 

随机推荐