Skip to content

Instantly share code, notes, and snippets.

@ixiyang
Last active August 29, 2015 14:04
Show Gist options
  • Save ixiyang/f7b3f35e021700f4a06c to your computer and use it in GitHub Desktop.
Save ixiyang/f7b3f35e021700f4a06c to your computer and use it in GitHub Desktop.
webview file upload,handle 4.4.x
-keepclassmembers class com.cofco.survey.activity.WebFragment$WebAppInterface {
<methods>;
}
-keepclassmembers class * {
# private static final int FILECHOOSER_RESULTCODE;
public void openFileChooser(android.webkit.ValueCallback,java.lang.String,java.lang.String);
public void openFileChooser(android.webkit.ValueCallback,java.lang.String);
public void openFileChooser(android.webkit.ValueCallback);
public void processHTML(java.lang.String);
public void saveCollapseState(int, boolean);
public void onResume(android.content.Context);
public void onPause(android.content.Context);
}
public class WebFragment extends Fragment implements OnRefreshListener<WebView> {
public static final String TAG = "WebFragment";
public static final String URL = "url";
public static final String IS_SINGLE_COLUMN = "is_single_column";
private String url;
PullToRefreshWebView refreshWebView;
private WebView webView;
private ProgressBar progressBar;
private boolean isSingleColumn;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
private final static int FILECHOOSER_RESULTCODE_X = 2;
public static WebFragment sInstance;
public static WebFragment newInstance(String url) {
WebFragment webFragment = new WebFragment();
Bundle bundle = new Bundle();
bundle.putString(URL, url);
webFragment.setArguments(bundle);
sInstance = webFragment;
return webFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sInstance = this;
Bundle bundle = getArguments();
if (bundle != null) {
url = bundle.getString(URL);
isSingleColumn = bundle.getBoolean(IS_SINGLE_COLUMN);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, null);
refreshWebView = (PullToRefreshWebView) view
.findViewById(R.id.webview_content);
webView = refreshWebView.getRefreshableView();
refreshWebView.setOnRefreshListener(this);
progressBar = (ProgressBar) view.findViewById(R.id.webview_progress);
setting();
return view;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Loger.info(TAG, url);
if (!TextUtils.isEmpty(url)) {
webView.loadUrl(url);
// webView.loadUrl("http://www.baidu.com");
}
}
private void setting() {
webView.setWebChromeClient(new CustomChromeClient());
webView.setWebViewClient(new CustomWebViewClient());
webView.setBackgroundColor(0);
WebviewSet.allowHttps(webView);
webView.addJavascriptInterface(new WebAppInterface(getActivity()),
"Android");
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setBuiltInZoomControls(false);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
settings.setUseWideViewPort(true);
} else {
settings.setUseWideViewPort(false);
}
if (isSingleColumn)
settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
else {
// settings.setBuiltInZoomControls(true);
// settings.setUseWideViewPort(true);
settings.setLoadsImagesAutomatically(true);
webView.setInitialScale(1);
}
}
/** 在webview内点击超链接直接在webview打开 */
private final class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// view.loadUrl("javascript:alert('Hello World!')");
view.loadUrl(url);
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(getActivity(), "fail to load content",
Toast.LENGTH_SHORT).show();
}
}
private final class CustomChromeClient extends WebChromeClient {
@Override
public void onReceivedTitle(WebView view, String title) {
// 如果接收到标题改变则修改界面标题
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress < 100
&& refreshWebView.getState() != State.REFRESHING) {
progressBar.setVisibility(View.VISIBLE);
} else
progressBar.setVisibility(View.GONE);
}
// 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);
}
@Override
public boolean onJsAlert(WebView view, String url, String message,
final JsResult result) {
new AlertDialog.Builder(getActivity())
// .setTitle("提示")
.setMessage(message)
.setPositiveButton("确定", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
@Override
public boolean onJsConfirm(WebView view, String url, String message,
final JsResult result) {
new AlertDialog.Builder(getActivity())
// .setTitle("JavaScript Confirm Alert !")
.setMessage(message)
.setPositiveButton("确定", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
@Override
public boolean onJsPrompt(WebView view, String url, String message,
String defaultValue, final JsPromptResult result) {
new AlertDialog.Builder(getActivity())
// .setTitle("JavaScript Prompt Alert !")
.setMessage(message)
.setPositiveButton("确定", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
}
@Override
public void onDestroy() {
webView.setVisibility(View.GONE);
sInstance = null;
super.onDestroy();
}
public WebView getWebView() {
return webView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
System.err.println("onactivityresult-----------");
if (requestCode == FILECHOOSER_RESULTCODE) {// pre 4.4
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else if (requestCode == FILECHOOSER_RESULTCODE_X
&& resultCode == Activity.RESULT_OK && intent != null) {// handle
// 4.4.X
String imgPath = getPath(intent.getData());
// Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
Bitmap bitmap;
try {
bitmap = BitmapUtil.decodeSampledBitmapFromPath(imgPath,
ViewSizeUtil.getScreenSize(getActivity())[1],
ViewSizeUtil.getScreenSize(getActivity())[0]);
} catch (Exception e) {
System.gc();
bitmap = BitmapUtil.decodeSampledBitmapFromPath(imgPath,
ViewSizeUtil.getScreenSize(getActivity())[1],
ViewSizeUtil.getScreenSize(getActivity())[0]);
}
if (bitmap == null) {
Toast.makeText(getActivity(), "图片地址无效,请重新选择",
Toast.LENGTH_SHORT).show();
return;
}
int size = sizeOf(bitmap);
bitmap.recycle();
System.err.println("size====>" + size);
// if (size > 2 * 1024 * 1024) {
// Toast.makeText(getActivity(), "图片不能超过2M",
// Toast.LENGTH_SHORT).show();
// } else {
// // upload
// }
uploadImg(imgPath);
}
}
public void uploadImg(String path) {
final FormFile formFile;
final File file;
if (!TextUtils.isEmpty(path)) {
file = new File(path);
if (!file.exists()) {
Toast.makeText(getActivity(), R.string.sd_nonecard,
Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
formFile = new FormFile(compressPic(file), file.getName(),
"Filedata", "application/octet-stream");
} else {
formFile = null;
return;
}
new Thread(new Runnable() {
@Override
public void run() {
String result = null;
// String url = NetApi.createUrl("User","edit_user_profile");
String url = SurveyApi.uploadImg();
Loger.info(TAG, "url=" + url);
HashMap<String, String> param = new HashMap<String, String>();
try {
result = FormPost.post(url, param, formFile);
Loger.info(TAG, "upload img result:" + result);
Message message = handler.obtainMessage(1, result);
handler.sendMessage(message);
} catch (Exception e) {
Message message = handler.obtainMessage(0, result);
handler.sendMessage(message);
}
}
}).start();
}
private static class ResultModel extends QMBaseModel {
int isSuccess;
String path;
int attachId;
String msg;
public int getIsSuccess() {
return isSuccess;
}
public void setIsSuccess(int isSuccess) {
this.isSuccess = isSuccess;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getAttachId() {
return attachId;
}
public void setAttachId(int attachId) {
this.attachId = attachId;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
private static class ResultParser extends Parser<QMBaseModel> {
@Override
public List<QMBaseModel> parseJSON(JSONObject jsonObject)
throws JSONException {
List<QMBaseModel> list = new ArrayList<QMBaseModel>();
if (jsonObject.has("data")) {
JSONArray ja = jsonObject.getJSONArray("data");
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
ResultModel result = parseToResultModel(jo);
list.add(result);
}
} else {
ResultModel result = parseToResultModel(jsonObject);
list.add(result);
}
return list;
}
public ResultModel parseToResultModel(JSONObject jo) {
ResultModel result = new ResultModel();
if (jo != null) {
result.setAttachId(jo.optInt("attach_id"));
result.setIsSuccess(jo.optInt("success"));
result.setMsg(jo.optString("message"));
result.setPath(jo.optString("image_src"));
}
return result;
}
}
private static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
sInstance.progressBar.setVisibility(View.GONE);
if (msg.what == 1 && msg.obj != null) {
System.err.println("upload img====" + msg.obj);
try {
ResultModel result = (ResultModel) new ResultParser()
.parseJSON(new JSONObject((String) msg.obj)).get(0);
if (result != null && result.isSuccess == 1) {
// success
String js = "javascript:AndroidUploadCallback('"
+ result.getPath() + "','"
+ result.getAttachId() + "')";
System.err.println("js======>" + js);
sInstance.webView.loadUrl(js);
} else if (result != null) {
Toast.makeText(sInstance.getActivity(), "图片上传失败",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(sInstance.getActivity(), "上传失败",
Toast.LENGTH_SHORT).show();
}
}
}
};
private static InputStream compressPic(File file) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 返回bm为空
// 获取这个图片的宽和高
BitmapFactory.decodeFile(file.getPath(), options);// 此时返回bm为空
Bitmap localBitmap = null;
for (int i = 0;; i++) {
if ((options.outWidth >> i > 1024)
|| (options.outHeight >> i > 1024))
continue;
int j = i;
options.inSampleSize = (int) Math.pow(2.0D, j);
options.inJustDecodeBounds = false;
localBitmap = BitmapFactory.decodeFile(file.getPath(), options);
if (localBitmap != null)
break;
Log.e(TAG, "Bitmap decode error!");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
localBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
localBitmap.recycle();
return new ByteArrayInputStream(baos.toByteArray());
}
@SuppressLint("NewApi")
protected int sizeOf(Bitmap data) {
try {
return data.getByteCount();
} catch (Exception e) {
}
return 0;
}
public String getPath(Uri uri) {
String siPath;
// 1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null,
null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
siPath = cursor.getString(column_index);
} else {
siPath = null;
}
if (siPath == null) {
// 2:OI FILE Manager --- call method: uri.getPath()
siPath = uri.getPath();
}
return siPath;
}
public static class WebAppInterface {
Context mContext;
public WebAppInterface(Context context) {
mContext = context;
}
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public String test() {
return "hello world";
}
@JavascriptInterface
public void openFileChooser() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
sInstance.startActivityForResult(
Intent.createChooser(i, "File Chooser"),
FILECHOOSER_RESULTCODE_X);
}
@JavascriptInterface
public void completeSurvey() {
sInstance.getActivity().finish();
}
@JavascriptInterface
public void completeInfoInit() {
sInstance.getActivity().setResult(Activity.RESULT_OK);
sInstance.getActivity().finish();
}
}
@Override
public void onRefresh(final PullToRefreshBase<WebView> refreshView) {
webView.reload();
refreshView.postDelayed(new Runnable() {
@Override
public void run() {
refreshView.onRefreshComplete();
}
}, 2 * 1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment