选择Web视图中的文件无法打开

时间:2017-06-23 12:25:44

标签: android webview

我正在使用WebView在Android应用中打开我的网站,一切正常,但当我点击选择文件按钮上传图片时,该按钮无法点击。在我的网站上有一个上传图片的选项,该用户需要上传图片,但选择文件按钮没有被点击进入应用程序。

    package com.example.roomsarehere.roomsarehere;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.net.URI;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {





//initializing WebView
private WebView mwebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //WebView
    mwebView = (WebView) findViewById(R.id.myWebView);
    WebSettings webSettings = mwebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    //improve webView performance
    mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    mwebView.getSettings().setAppCacheEnabled(true);
    mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    webSettings.setUseWideViewPort(true);
    webSettings.setSavePassword(true);
    webSettings.setSaveFormData(true);
    webSettings.setEnableSmoothTransition(true);


    mwebView.loadUrl("http://www.roomsarehere.com");
    //force links open in webview only
    mwebView.setWebViewClient(new MyWebviewClient());

}


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
        mwebView.loadUrl("http://www.newsweek.com/us");
    } else if (id == R.id.nav_gallery) {
        mwebView.loadUrl("http://www.newsweek.com/world");
    } else if (id == R.id.nav_manage) {
        mwebView.loadUrl("http://www.newsweek.com/tech-science");
    } else if (id == R.id.nav_slideshow) {
        mwebView.loadUrl("http://www.newsweek.com/sports");
    } else if (id == R.id.nav_share) {
        mwebView.loadUrl("http://www.newsweek.com/about-newsweek");
    } else if (id == R.id.nav_send) {
        mwebView.loadUrl("http://www.newsweek.com/contact");
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

private class MyWebviewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("www.roomsarehere.com")) {
            //open url contents in webview
            return false;
        } else {
            //here open external links in external browser or app
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }

    }
    //ProgressDialogue
    ProgressDialog pd = null;

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        pd=new ProgressDialog(MainActivity.this);
        pd.setTitle("Please Wait..");
        pd.setMessage("Content is Loading..");
        pd.show();
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        pd.dismiss();
        super.onPageFinished(view, url);
    }
}
//goto previous page when pressing back button

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mwebView.canGoBack()) {
                    mwebView.goBack();
                } else {
                    finish();
                }
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}
}

1 个答案:

答案 0 :(得分:1)

使用此代码。

声明这些变量全局

private ValueCallback<Uri[]> afterLolipop;
private ValueCallback<Uri> mUploadMessage;

然后在您的WebView添加WebChromeClient列表器:

     webView.setWebChromeClient(new WebChromeClient() {

        // For Android 3.0+ - undocumented method
        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);
                Log.i("DEBUG", "Open file Chooser");
                mUploadMessage = uploadMsg;
            }

        // For Android > 4.1 - undocumented method
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(pickPhoto , 101);

        }

        // For Android > 5.0
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {

                startActivityForResult(fileChooserParams.createIntent(), 101);


        }

    });

onActivityResult()

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

    }

希望它能起作用..