Android WebView fileupload

Android WebView fileupload

Будучи android полностью кастомным, то при добавление элемента управления WebView вы обнаружите что по умолчанию он не умеет загружать файлы в поля file upload и ему потребуется описать логику поведения.

1. Добавим виджет Webview на наш layout

<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" >

<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
android:layout_gravity="center" />
</FrameLayout>
Виджет будет растянут по всей странице.
2. Переходим к редактированию кода. В контексте данной активности добавляем следующий код.

WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
..
..
..
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(false);
webView.setWebViewClient(new Callback());
webView.getSettings().setAllowFileAccess(true);
webView.loadUrl(res.getString(R.string.url));

webView.setWebChromeClient(new WebChromeClient() {


public void onExceededDatabaseQuota(String url, String
databaseIdentifier, long currentQuota, long estimatedSize, long
totalUsedQuota, QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(estimatedSize + 65536);
}

@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
this.openFileChooser(uploadMsg);
}

@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
this.openFileChooser(uploadMsg);
}

public void openFileChooser(ValueCallback<Uri> uploadMsg) {

mUploadMessage = uploadMsg;
MainActivity.this.openImageIntent(uploadMsg);
}


@Override
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {

if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;

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 = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException 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, "Select image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

return true;
}


И добавить метод обработчик выбранных файлов
// return here when file selected from camera or from SD Card
@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {

// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

if(requestCode==FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}

Uri result=null;

try{
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
}
catch(Exception e) {
Toast.makeText(getApplicationContext(), "activity :"+e, Toast.LENGTH_LONG).show();
}

mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}

} // end of code for all versions except of Lollipop

// start of code for Lollipop only
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}

Uri[] results = null;

// check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// if there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}

mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;

} // end of code for Lollipop only

}