2015年10月14日 星期三

Fragment WebView 上傳檔案 判斷5.0 or 5.0以下 用哪種方法

Layout

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"             xmlns:tools="http://schemas.android.com/tools"             android:id="@+id/container"             android:layout_width="match_parent"             android:layout_height="match_parent"             tools:context=".MainActivity"             tools:ignore="MergeRootFrame" />


fragment_main.xml

<?xml version="1.0"?><LinearLayout android:id="@+id/main_parent_view" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:orientation="vertical">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<WebView android:id="@+id/mwebview_oil" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/>
<RelativeLayout android:layout_width="match_parent" android:layout_height="44dp" android:background="#00000000" android:orientation="horizontal">
>
<ImageButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/lt_webar_btn_pre" />
<ImageButton android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/button" android:background="@drawable/lt_webbar_button_next"/>
<ImageButton android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:background="@drawable/lt_webar_btn_refresh"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>



Activiy

MainActivity

public class MainActivity extends Activity {
    private WebView mCityStroeWebView;
    Context context = MainActivity.this;
    ProgressDialog myDialog = null;
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;
    private  String uri ;
    private boolean isNetWork = true;
    private boolean isFirst = true;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {

            getFragmentManager().beginTransaction()
                    .add(R.id.container, new MainFragment())
                    .commit();
        }
//        init();    }
    @Override    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

MainFragment

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainFragment extends Fragment {

    private static final String TAG = MainFragment.class.getSimpleName();

    public static final int INPUT_FILE_REQUEST_CODE = 1;
    public static final String EXTRA_FROM_NOTIFICATION = "EXTRA_FROM_NOTIFICATION";
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 2;//給的值不能一樣 不然只會跑另一個
    private WebView mWebView;
    private ValueCallback<Uri[]> mFilePathCallback;
    private String mCameraPhotoPath;

    //    private Button ;    public MainFragment() {
    }

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        int sysVersion = Integer.parseInt(Build.VERSION.SDK);
        Log.e("sysVersion", sysVersion + "");
        mWebView = (WebView) rootView.findViewById(R.id.mwebview_oil);

        setUpWebViewDefaults(mWebView);

        // Check whether we're recreating a previously destroyed instance        if (savedInstanceState != null) {
            // Restore the previous URL and history stack            mWebView.restoreState(savedInstanceState);
        }
        if (sysVersion <= 19) {
            mWebView.setWebChromeClient(new MyWebClient());
        } else {
            mWebView.setWebChromeClient(new WebChromeClient() {
                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(getActivity().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, "Image Chooser");
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

                    startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

                    return true;
                }
            });
        }


        // Load the local index.html file        if (mWebView.getUrl() == null) {
            mWebView.loadUrl("http://ur-dev.hxcld.com/main/login");
        }

        return rootView;
    }

    /**     * More info this method can be found at     * http://developer.android.com/training/camera/photobasics.html     *     * @return     * @throws IOException     */    private File createImageFile() throws IOException {

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(
                imageFileName,  /* prefix */                ".jpg",         /* suffix */                storageDir      /* directory */        );
        return imageFile;
    }

    /**     * Convenience method to set some generic defaults for a     * given WebView     *     * @param webView     */    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setUpWebViewDefaults(WebView webView) {
        WebSettings settings = webView.getSettings();

        // Enable Javascript        settings.setJavaScriptEnabled(true);

        // Use WideViewport and Zoom out if there is no viewport defined//        settings.setUseWideViewPort(true);//自適螢幕大小//        settings.setLoadWithOverviewMode(true);
        // Enable pinch to zoom without the zoom buttons        settings.setBuiltInZoomControls(true);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
            // Hide the zoom controls for HONEYCOMB+            settings.setDisplayZoomControls(false);
        }

        // Enable remote debugging via chrome://inspect        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        // We set the WebViewClient to ensure links are consumed by the WebView rather        // than passed to a browser if it can        mWebView.setWebViewClient(new WebViewClient());
    }

    @Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }

        if (requestCode != INPUT_FILE_REQUEST_CODE || 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;
        return;
    }


    public class MyWebClient extends WebChromeClient {
        // 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<Uri> 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);
        }

    }
}

下載位置




2015年10月8日 星期四

WebView 顯示讀取條 寫法

Context context = MainActivity.this;
ProgressDialog myDialog = null;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;



   mCityStroeWebView.setWebViewClient(new WebViewClient() {
            @Override            public void onPageFinished(WebView view, String url) {
                handler.sendEmptyMessage(0);
                super.onPageFinished(view, url);
            }
        });
        if (checkInternet(context) == true) {

//            progressbar.setVisibility(View.VISIBLE);            myDialog = ProgressDialog.show                    (
                            context,
                            "連線中,請稍候",
                            "載入中",
                            true                    );

            mCityStroeWebView.loadUrl(uri);
            fun_thread();
        } else {
//            Toast.makeText(context, "請檢查是否連接網路", Toast.LENGTH_SHORT).show();
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle(getString(R.string.Network_status))
                    .setMessage(getString(R.string.no_network))
                    .setCancelable(false)
                    .setPositiveButton(getString(R.string.setting), new DialogInterface.OnClickListener() {

                        @Override                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub                            Intent settintIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                            startActivity(settintIntent);

                        }
                    })
                    .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

                        @Override                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub                            MainActivity.this.finish();
                        }
                    })
                    .show();
        }


public void fun_thread() {
        new Thread() {
            public void run() {
                try {
                    //15後仍未讀到網頁, 則顯示網路雍塞中                    for (int i = 0; i < 15; i++) {
                        sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //為了能與handler建立關聯進而控制Progress Dialog / Progress Bar的關閉                Message m = new Message();
                Bundle b = m.getData();
                b.putInt("WHICH", 1);
                m.setData(b);
                handler.sendMessage(m);
            }
        }.start();
    }

    /*   * 透過HandlerProgress Dialog / Progress Bar關閉
   */    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int which = msg.getData().getInt("WHICH");
//            progressbar.setVisibility(View.GONE);            myDialog.dismiss();
            if (which == 1) {
//                Toast.makeText(context, "網路忙線中!!", Toast.LENGTH_SHORT).show();            }
        }
    };

    /*      * 判別網路連線狀態
      * 需在Manifest.xml加入權限:ACCESS_NETWORK_STATE      */    public boolean checkInternet(android.content.Context context) {
        boolean result = false;
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connManager.getActiveNetworkInfo();
        if (info == null || !info.isConnected()) {
            Log.d("webview", "info == null || !info.isConnected()");
            result = false;
        } else {
            if (!info.isAvailable()) {
                Log.d("webview", "!info.isAvailable()");
                result = false;
            } else {
                Log.d("webview", "info.isAvailable()");
                result = true;
            }
        }
        return result;
    }


如何在WebView 上 上傳檔案

mWebView.setWebChromeClient(new MyWebClient());



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




    public class MyWebClient extends WebChromeClient {
        // 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<Uri> 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);
        }
    }
}


主要就是自定義了WebChromeClient,然而測試時發現在4.4以上的Andr​​oid版本依然不可以,搜了下openFileChooser方法在4.4以後不是public的,所以以後不建議這種直接在WebView上傳文件的做法。

2015年10月6日 星期二

TextView 限制字數寫法


android:maxEms="6"  //限制 最多可以出現幾個字串
android:singleLine="true" / /是否為單行  true 為是  false 為否
android:ellipsize="end"  // 後面省略的會變成....