public class cloud extends Activity
{
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.cloud);
setTitle("AmigoFriends");
WebView myWebView01 = (WebView)findViewById(R.id.webView1);
String strURI = "http://amigofriends.mis.nsysu.edu.tw/e/mobile/";
myWebView01.loadUrl(strURI);
myWebView01.setWebViewClient(new WebViewClient(){});
WebSettings websettings = myWebView01.getSettings();
websettings.setJavaScriptEnabled(true);
websettings.setSupportZoom(true);
websettings.setBuiltInZoomControls(true);
websettings.setLoadsImagesAutomatically(true);
WebSettings settings = myWebView01.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
WebView myWebView01 = (WebView)findViewById(R.id.webView1);
if ((keyCode == KeyEvent.KEYCODE_BACK) && event.getRepeatCount() == 0)
{
boolean CloseYN;
if(myWebView01.canGoBack())
{
CloseYN = false;
myWebView01.goBack();
}
else
{
CloseYN = true;
}
event.startTracking();
return CloseYN;
}
return super.onKeyDown(keyCode, event);
}
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
protected class CustomWebChromeClient extends WebChromeClient
{
// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
openFileChooser(uploadMsg);
}
// Andorid 3.0 +
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
{
openFileChooser(uploadMsg);
}
//Android 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "Image Browser"), FILECHOOSER_RESULTCODE);
}
}
class MyWebChromeClient extends WebChromeClient
{
// The undocumented magic method override
// Eclipse will swear at you if you try to put #Override here
public void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
cloud.this.startActivityForResult(
Intent.createChooser(i, "Image Browser"),
FILECHOOSER_RESULTCODE);
}
}
}
Related
This question already has an answer here:
Unable connect to a HTTP URL in Android 10
(1 answer)
Closed 2 years ago.
I have a problem with this script.
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private WebView webView;
private SwipeRefreshLayout refreshLayout;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView1);
WebSettings mWebSettings = webView.getSettings();
mWebSettings.setJavaScriptEnabled(true);
mWebSettings.setSupportZoom(false);
mWebSettings.setAllowFileAccess(true);
mWebSettings.setAllowFileAccess(true);
mWebSettings.setAllowContentAccess(true);
webView.setWebViewClient(new MyBrowser());
webView.loadUrl("http://www.mypage.com");
webView.setWebChromeClient(new WebChromeClient() {
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
Toast.makeText(MainActivity.this.getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
#Override
public void onRefresh() {
webView.reload();
refreshLayout.setRefreshing(false);
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
view.loadData("Page not found", "text/html", "utf-8");
super.onReceivedError(view, request, error);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
if (requestCode == REQUEST_SELECT_FILE)
{
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
}
else if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
else
Toast.makeText(MainActivity.this.getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}
}
It's running well when I run it on under android 8. But it always shows an error page not found if I run at android 10. Someone can tell me why loadUrl not work at this case? Thank you for you help before...
I think its problem from your url
on android 9 onward it required url using https, if you using http it will rejected
for example:
webView.loadUrl("https://www.mypage.com");
or you can add permission android:usesCleartextTraffic="true" on your manifest but its not guarented work but worth to try
manifest.xml
<manifest>
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<activity> your code </activity>
</application>
</manifest>
Try this following code :
public class Website extends AppCompatActivity {
WebView webView;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
webView.setWebViewClient(new myWebclient());
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("https://yourURL.com/");
//check permission in case downloading file from webview
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, 1);
}
}
//method for downloading file to internal storage Download folder
webView.setDownloadListener(new DownloadListener()
{
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}});
}
public class myWebclient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pDialog = new ProgressDialog(Website.this);
pDialog.setMessage("Please Wait");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
//method to go back to previous page on click back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
The application consists of a simple splash screen and webview. But when it comes to the webview side, there is a problem of freezing in the application. It doesn't work exactly when I scroll. There is no freeze in the normal browser. What is the problem
Splash Screen
public class SplashScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
finish();
}
}, 1200);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
private final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.loadUrl("https://dokuzlama.com");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowContentAccess(true);
webView.setWebViewClient(new Callback());
webView.setWebChromeClient(new WebChromeClient()
{
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
Toast.makeText(MainActivity.this.getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
//eski---- > Toast.makeText(getActivity().getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Uygulama yüklenemedi", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else
Toast.makeText(MainActivity.this.getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
//eski____ Toast.makeText(getActivity().getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}
#Override
public void onBackPressed() {
if (webView.canGoBack()){
webView.goBack();
} else {
super.onBackPressed();
}
}
}
I researched and analyzed a lot but I couldn't find
Try enabling hardware acceleration in manifest in your activity
android:hardwareAccelerated="true"
I'm setting up my webview app and I would like "choose file" button to be able to upload pictures from my phone, but now that button does not have any function or does not work. Please if anyone can help me, thank you in advance!
This is from MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://example.com");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
And this is from AndroidManifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Follow the stated code below :
public class MainActivity extends Activity {
private WebView webView;
private String urlStart = "http://www.example.com/mobile/";
private static final int FILECHOOSER_RESULTCODE = 2888;
private ValueCallback<Uri> mUploadMessage;
//Camera parameters
private Uri mCapturedImageURI = null;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setAllowFileAccess(true);
webView.loadUrl(urlStart);
webView.setWebChromeClient(new WebChromeClient() {
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
try{
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();
String mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
System.currentTimeMillis() + ".jpg";
mCapturedImageURI = Uri.fromFile(new File(mCameraFilePath));
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { cameraIntent });
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
catch(Exception e){
Toast.makeText(getBaseContext(), "Camera Exception:"+e, Toast.LENGTH_LONG).show();
}
}
// For Android < 3.0
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg ) {
openFileChooser(uploadMsg, "");
}
// For Android > 4.1.1
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
openFileChooser(uploadMsg, acceptType);
}
public boolean onConsoleMessage(ConsoleMessage cm) {
onConsoleMessage(cm.message(), cm.lineNumber(), cm.sourceId());
return true;
}
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
Log.d("androidruntime", "www.example.com: " + message);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// TODO Auto-generated method stub
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 = intent == null ? mCapturedImageURI : intent.getData();
}
} catch(Exception e) {
Toast.makeText(getApplicationContext(), "activity :"+e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
You have to set WebChromeClient for Choose File in webview
CODE IS HERE
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
private String url = "www.example.com";
private ValueCallback<Uri> msgUpload;
private final static int CHOOSER_FILE_RESULT_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
initViews();
setListeners();
}
private void initViews() {
webView = findViewById(R.id.webView);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setAllowFileAccess(true);
}
private void setListeners()
{
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("about:blank");
view.clearHistory();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
msgUpload = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(
Intent.createChooser(i, "File Browser"),
CHOOSER_FILE_RESULT_CODE);
}
//For Android 4.1 and above
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
msgUpload = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), CHOOSER_FILE_RESULT_CODE);
}
});
webView.loadUrl(url);
final MyJavaScriptInterface myJavaScriptInterface
= new MyJavaScriptInterface(this);
webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (webView.canGoBack() == true) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == CHOOSER_FILE_RESULT_CODE) {
if (null == msgUpload) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
msgUpload.onReceiveValue(result);
msgUpload= null;
}
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
#JavascriptInterface
public void openAndroidDialog() {
AlertDialog.Builder myDialog
= new AlertDialog.Builder(WebViewActivity.this);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
I have a button choose files in website, when you press the button on your computer it works and when you press the button on the phone does not work what solution, the site shows using WebView
mywebsite = (WebView)findViewById(R.id.mywebsite);
pd_loading = (ProgressBar)findViewById(R.id.pd_loading);
mywebsite.getSettings().setLoadsImagesAutomatically(true);
mywebsite.getSettings().setJavaScriptEnabled(true);
mywebsite.setWebViewClient(new WebViewClient());
mywebsite.loadUrl(Information.URL_Home);
mywebsite.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view ,String url)
{
pd_loading.setVisibility(View.GONE);
mywebsite.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toasty.error(Home.this,"",Toast.LENGTH_SHORT,true).show();
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), 101);
mUploadMessage = uploadMsg;
}
// For Android > 4.1 - undocumented method
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, "");
}
// For Android > 5.0
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
startActivityForResult(fileChooserParams.createIntent(), 101);
return true;
}
});
onActivittyResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case 101:
if (resultCode == RESULT_OK) {
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(result);
} else if (afterLolipop != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
afterLolipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
afterLolipop = null;
}
}
mUploadMessage = null;
}
}
}
these codes don't work I just want to choose a picture of a computer I hope help me thanks
When I faced a similar kind of issue, I have made use of setWebChromeClient() method found from this souce.
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.apache.http.util.EncodingUtils;
public class BrowserScreen extends Activity {
private WebView webView;
private String url = "url";
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.browser_activity);
initFields();
setListeners();
}
public void initFields() {
// TODO Auto-generated method stub
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAllowFileAccess(true);
}
public void setListeners() {
// TODO Auto-generated method stub
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("about:blank");
view.clearHistory();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
}
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
webView.loadUrl(url);
final MyJavaScriptInterface myJavaScriptInterface
= new MyJavaScriptInterface(this);
webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (webView.canGoBack() == true) {
webView.goBack();
} else {
super.onBackPressed();
}
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
// webView.loadUrl("javascript:document.getElementById(\"Button3\").innerHTML = \"bye\";");
}
#JavascriptInterface
public void openAndroidDialog() {
AlertDialog.Builder myDialog
= new AlertDialog.Builder(BrowserScreen.this);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}
I have a problem.. :(
I have a custom webView implemented myself like an extends WebViewClient.
In the html side of the application I have a tag <input type='file' id='media' name='media' accept="image/*" capture="camera" /> but I can not make it works!
I follow a lot of tutorial but all of them use WebChromeclient; in my case, because the complexity of the application, I use a WebViewClient.
Is there a solution?
Please..
Here there is my class
public class MyWebView extends WebViewClient{
private static Context context;
private static HttpClient client;
private static SharedPreferences prefs;
public MyWebView(Context context, HttpClient client, SharedPreferences prefs){
super();
MyWebView.context = context;
MyWebView.client = client;
MyWebView.prefs = prefs;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//some operation with cookie
}
I was having the same issue for webview.
Let suppose ur html looks like
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
here is the whole which solved my problem
package com.example.webviewtest;
public class MainActivity extends Activity {
private WebView wv;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wv = new WebView(this);
wv.setWebViewClient(new WebViewClient());
wv.setWebChromeClient(new WebChromeClient() {
// The undocumented magic method override
// Eclipse will swear at you if you try to put #Override here
// For Android < 3.0
public void openFileChooser(ValueCallback uploadMsg) {
Log.i("For Android < 3.0", "called");
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg,
String acceptType) {
Log.i("For Android 3.0+", "called");
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg);
Log.i("For Android Jellybeans", "called");
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
});
setContentView(wv);
wv.loadUrl("http://blue.genetechz.com/qadir/");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
Log.i("onActivityResult", "called");
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage){
Log.i("if", "return called");
return;
}else{
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
Log.i("else", "inner Called");
}
} else {
Log.i("Else", "Called");
// super.onActivityResult(requestCode, resultCode, intent);
// IPlugin callback = this.activityResultCallback;
// if (callback != null) {
// callback.onActivityResult(requestCode, resultCode, intent);
// }
}
}
#Override
public void onBackPressed() {
if (wv.canGoBack() == true) {
wv.goBack();
} else {
MainActivity.this.finish();
}
}
}