首页 > 解决方案 > webview 应用程序:选择文件不起作用

问题描述

我正在设置我的 webview 应用程序,我希望“选择文件”按钮能够从我的手机上传图片,但现在该按钮没有任何功能或不起作用。如果有人可以帮助我,请提前谢谢!

这是来自 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();
    }
}

}

这是来自 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>

标签: androidwebviewandroid-webview

解决方案


请遵循以下规定的代码

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;
 }

}

推荐阅读