在android webview上上传文件

时间:2015-03-18 23:11:21

标签: java android webview

我是Android应用程序开发的新手,试图开发一个Web视图应用程序,但似乎无法让文件上传工作......请帮忙

这是我的网络视图代码

package com.example.project;

公共类WebActivity扩展了Activity {

private WebView wv;

private String LASTURL = "";

Menu myMenu = null;
private ProgressDialog dialog;
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;  
 }
 }  




/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().requestFeature(Window.FEATURE_PROGRESS);

    if (!InternetConnection.checkNetworkConnection(this)) {
        showAlert(this, "No Data Connection", "This Application requires an internet connection");
    } else {

        setContentView(R.layout.web_view);

        wv = (WebView) findViewById(R.id.web_view);

        WebSettings webSettings = wv.getSettings();
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(false);


        final Activity activity = this;

        // start ProgressDialog with "Page loading..."
        dialog = new ProgressDialog(activity);
        dialog.setMessage("Loading...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.show();

        wv.setWebChromeClient(new WebChromeClient() {


            public void onProgressChanged(WebView view, int progress) {
                // set address bar and progress
                // activity.setTitle( " " + LASTURL );
                // activity.setProgress( progress * 100 );

                if (progress == 100) {
                    // stop ProgressDialog after loading
                    dialog.dismiss();

                    // activity.setTitle( " " + LASTURL );
                }
            }
        });


        wv.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode,
                    String description, String failingUrl) {
                Toast.makeText(getApplicationContext(),
                        "Error: " + description + " " + failingUrl,
                        Toast.LENGTH_LONG).show();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.indexOf("mycitygist") <= 0) {
                    // the link is not for a page on my site, so launch
                    // another Activity that handles URLs
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri
                            .parse(url));
                    startActivity(intent);
                    return true;
                }
                return false;
            }
            /*****************************************************************/
            /*  Here the load of the page will start so we must launch the  */
            /*  ProgressDialog                                              */
            /*****************************************************************/                                             
            public void onPageStarted(WebView view, String url,
                    Bitmap favicon) {

                // this is what we should do
                dialog.setMessage("Loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                dialog.show();
                //
                LASTURL = url;
                view.getSettings().setLoadsImagesAutomatically(true);
                view.getSettings().setBuiltInZoomControls(true);
            }
            /*****************************************************************/
            /*  Here the load of the page will stop so we must dismiss the  */
            /*  ProgressDialog                                              */
            /*****************************************************************/ 
            public void onPageFinished(WebView view, String url) {
                // this is what we should do
                dialog.dismiss();

            }
        });
        wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        wv.setScrollbarFadingEnabled(false);
        wv.loadUrl("http://app.mycitygist.com/overview/");

    }

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
        wv.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    this.myMenu = menu;
    MenuItem item = menu.add(0, 1, 0, "Home");
    item.setIcon(R.drawable.home);
    MenuItem item2 = menu.add(0, 2, 0, "Back");
    item2.setIcon(R.drawable.arrowleft);
    MenuItem item3 = menu.add(0, 3, 0, "Reload");
    item3.setIcon(R.drawable.s);
    MenuItem item4 = menu.add(0, 4, 0, "Share");
    item4.setIcon(R.drawable.share);
    MenuItem item5 = menu.add(0, 5, 0, "Rate");
    item5.setIcon(R.drawable.vote);
    MenuItem item6 = menu.add(0, 6, 0, "Exit");
    item6.setIcon(R.drawable.close);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
        wv.loadUrl("http://http://app.mycitygist.com/overview/");
        break;
    case 2:
        if (wv.canGoBack()) {
            wv.goBack();
        }
        break;
    case 3:
        wv.loadUrl(LASTURL);
        break;
    case 4:
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("plain/text");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Check out this app I found.");
        startActivity(Intent.createChooser(sharingIntent,"Share using"));
        break;
    case 5:

        Intent marketIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(
                "http://market.android.com/details?id=" + getPackageName()));
              startActivity(marketIntent2);
            break;

    case 6:
        finish();
        break;

    }

    return true;
}



/**
 * Display a simple alert dialog with the given text and title.
 * 
 * @param context
 *            Android context in which the dialog should be displayed
 * @param title
 *            Alert dialog title
 * @param text
 *            Alert dialog message
 */
public void showAlert(Context context, String title, String text) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

    // set title
    alertDialogBuilder.setTitle( title);

    // set dialog message
    alertDialogBuilder
    .setMessage( text )
    .setCancelable(false)
    .setPositiveButton("OK",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int id) {
            // if this button is clicked, close
            // current activity
            finish();
        }
    })
    .create().show();

}

}

所以我在wv下添加了这段代码。 setWebChromeClient  //未记录的魔法方法覆盖
            //如果你试图把@Override放在这里,Eclipse会发誓你          //适用于Android 3.0及更高版本              public void openFileChooser(ValueCallback uploadMsg){

         mUploadMessage = uploadMsg;  
         Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
         i.addCategory(Intent.CATEGORY_OPENABLE);  
         i.setType("image/*");  
         WebActivity.this.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("*/*");
        WebActivity.this.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/*");  
            WebActivity.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), WebActivity.FILECHOOSER_RESULTCODE );

        }

    });  


    setContentView(wv);  


    }

    }

似乎无法使用这行代码编译应用程序,如果没有它,d app编译得很好并且运行良好但没有文件上传功能

1 个答案:

答案 0 :(得分:0)

请参阅此代码,我正在使用“文件选择”按钮来选择文件,稍后将在我的jsp中使用上载

void InsereNaPosicaoMaisBarata (list<int>& Rota, // <-- passed by reference
                                int vehicle, 
                                int no, 
                                DATA data, 
                                double &melhorDur, 
                                list <int>::iterator &melhorPos )