2017-02-12 11 views
1

Я новичок в android и теперь пытаюсь разработать веб-приложение. Я использую несколько дней, чтобы файл ввода-типа работал отлично в webview. Пока я не следую и не использую этот код для обработки выбора файла в webview.Handle file chooser android 6.0 webview

enter link description here

Когда я использую AVD Nexus с Gingerbeard и нажмите файл типа входного сигнала, он может показать две опции (камеры или галереи). Проблема заключается в том, что я использую AVD Nexus с 6.0 и нажмите файл типа ввода, он открывает файловый менеджер, не показывая камеру или галерею опций. Я хочу показать диалоговое окно ввода каждый раз, когда пользователь нажимает файл типа ввода.

Как это сделать? Спасибо за помощь.

ответ

2

Добавить это для Android 5.0 и выше

private static final int INPUT_FILE_REQUEST_CODE = 1; 

private Context mContext=YourActivity.this; 
private static final int REQUEST_CAMERA = 111; 

// For Android 5.0 

public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) 
{ 
    // Log.d(TAG,"ShowFileChooser For Android 5.0 "); 
    if (mFilePathCallback != null) { 
     mFilePathCallback.onReceiveValue(null); 
    } 
    mFilePathCallback = filePath; 
    if (Build.VERSION.SDK_INT >= 23) { 
     // Log.d(TAG,"ShowFileChooser For Android 5.0 SDK_INT>=23 chk permission"); 
     String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}; 
     if (!hasPermissions(mContext, PERMISSIONS)) { 
      ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_CAMERA); 
     } else { 
      //Log.d(TAG,"ShowFileChooser For Android 5.0 in IF SDK_INT>=23 permission grant"); 
      Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
      if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
       // Create the File where the photo should go 
       File photoFile = null; 
       try { 
        photoFile = Constant.create_file(); 
        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); 
       } catch (Exception ex) { 
        // Error occurred while creating the File 
        // Log.e(TAG, "Unable to create Image File", ex); 
       } 
       // Continue only if the File was successfully created 
       if (photoFile != null) { 
        mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); 
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
          Uri.fromFile(photoFile)); 
       } else { 
        takePictureIntent = null; 
       } 
      } 
      Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); 
      contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); 
      contentSelectionIntent.setType("image/*"); 
      Intent[] intentArray; 
      if (takePictureIntent != null) { 
       intentArray = new Intent[]{takePictureIntent}; 
      } else { 
       intentArray = new Intent[0]; 
      } 
      Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); 
      chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); 
      chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); 
      chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); 
      startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); 
     } 
    } else { 
     // Log.d(TAG,"ShowFileChooser For Android 5.0 in else SDK_INT>=23"); 
     if (mFilePathCallback != null) { 
      mFilePathCallback.onReceiveValue(null); 
     } 
     mFilePathCallback = filePath; 
     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
      // Create the File where the photo should go 
      File photoFile = null; 
      try { 
       photoFile = Constant.create_file(); 
       takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); 
      } catch (Exception ex) { 
       // Error occurred while creating the File 
       // Log.e(TAG, "Unable to create Image File", ex); 
      } 
      // Continue only if the File was successfully created 
      if (photoFile != null) { 
       mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); 
       takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
         Uri.fromFile(photoFile)); 
      } else { 
       takePictureIntent = null; 
      } 
     } 
     Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); 
     contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); 
     contentSelectionIntent.setType("image/*"); 
     Intent[] intentArray; 
     if (takePictureIntent != null) { 
      intentArray = new Intent[]{takePictureIntent}; 
     } else { 
      intentArray = new Intent[0]; 
     } 
     Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); 
     chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); 
     chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); 
     chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); 
     startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); 
    } 
    // Double check that we don't have any existing callbacks 
    return true; 
} 

Проверить права доступа для зефира

private static boolean hasPermissions(Context context, String... permissions) { 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) { 
     for (String permission : permissions) { 
      if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { 
       return false; 
      } 
     } 
    } 
    return true; 
} 

Получить права Результат

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    switch (requestCode) { 

     case REQUEST_CAMERA: { 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
        // Create the File where the photo should go 
        File photoFile = null; 
        try { 
         photoFile = Constant.create_file(); 
         takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); 
        } catch (Exception ex) { 
        } 
        // Continue only if the File was successfully created 
        if (photoFile != null) { 
         mCameraPhotoPath = "file:" + photoFile.getAbsolutePath(); 
         takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); 
        } else { 
         takePictureIntent = null; 
        } 
       } 
       Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); 
       contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); 
       contentSelectionIntent.setType("image/*"); 
       Intent[] intentArray; 
       if (takePictureIntent != null) { 
        intentArray = new Intent[]{takePictureIntent}; 
       } else { 
        intentArray = new Intent[0]; 
       } 
       Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); 
       chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); 
       chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); 
       chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); 
       startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE); 

       //reload my activity with permission granted or use the features what required the permission 
      } else { 
       Patient_appointment.setWebChromeClient(new ChromeClient()); 
       Toast.makeText(mContext, "The app was not allowed to write to your storage", Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 
} 
+0

Привет, что mContext? И значение для REQUEST_CAMERA? Мое имя activity - InventoryDataEditor. –

+0

Контекст mContext = InventoryDataEditor.this; закрытый статический окончательный int REQUEST_CAMERA = 111; – user2025187