Java tutorial
/* * Copyright (c) 2005, 2014, EVECOM Technology Co.,Ltd. All rights reserved. * EVECOM PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * */ package net.evecom.android.web; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.regex.Pattern; import net.evecom.android.R; import net.evecom.android.util.HttpUtil; import net.evecom.android.util.ShareUtil; import net.tsz.afinal.FinalHttp; import net.tsz.afinal.http.AjaxCallBack; import net.tsz.afinal.http.HttpHandler; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EncodingUtils; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.DialogInterface.OnKeyListener; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Message; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.DownloadListener; import android.webkit.GeolocationPermissions; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.ZoomDensity; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; /** * MessagePostWebActivity * * @author Mars zhang * */ public class WebdbActivity extends Activity { /** MemberVariables */ private WebView webView; /** MemberVariables */ ProgressDialog dialog = null; /** MemberVariables */ protected Context mContext; /** */ private String temp = "15"; /** */ private AlertDialog dialogPress; /** */ private ImageView imageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; temp = HttpUtil.getPageSize(this); setContentView(R.layout.message_post_web); imageView = (ImageView) findViewById(R.id.image_view_at_web); webView = (WebView) this.findViewById(R.id.wv_oauth_message); CookieSyncManager.createInstance(this); CookieSyncManager.getInstance().startSync(); CookieManager.getInstance().removeSessionCookie(); /** * WebViewJavaScript */ webView.getSettings().setJavaScriptEnabled(true); /** * loadUrl() */ HelloWebViewClient client = new HelloWebViewClient(); webView.setWebViewClient(client); dialog = ProgressDialog.show(WebdbActivity.this, null, ".."); dialog.setCancelable(true); // http://harlan-pc/fzaj/emergency/mobileWebApp/publicInfo/login.do?userName=zf1&userPwd=1 // webView.loadUrl("http://www.baidu.com"); // String url = HttpUtil.BASE_PC_URL // String url =HttpUtil.BASE_PC_URL+"loginController/messageLogin"; String url = HttpUtil.BASE_PC_URL + "mobile/loginController/eventlistLogin"; // post // http://wangzy:8081/gssms/mobile/loginController/eventlistLogin?loginname=sysadmin&pwd=888888 // String postDate = "loginname=sysadmin&pwd=888888"; String postDate = "loginname=" + ShareUtil.getString(getApplicationContext(), "SESSION", "USERNAME", "") + "&pwd=" + ShareUtil.getString(getApplicationContext(), "SESSION", "PASSWORD", "") + "&pageSize=" + temp; // webView.postUrl(url, postData) postDatabyte[] // EncodingUtils.getBytes(data, charset) webView.postUrl(url, EncodingUtils.getBytes(postDate, "BASE64")); // webView.setDownloadListener(new MyWebViewDownLoadListener()); WebSettings webSettings = webView.getSettings(); webSettings.setSupportZoom(true); webSettings.setJavaScriptEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); webSettings.setBuiltInZoomControls(true);// support zoom // webSettings.setPluginsEnabled(true);//support flash webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); // webSettings.setPluginsEnabled(true); //(flash) /** */ // // webSettings.setDatabaseEnabled(true); String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); // webSettings.setGeolocationEnabled(true); // webSettings.setGeolocationDatabasePath(dir); // webSettings.setDomStorageEnabled(true); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); int mDensity = metrics.densityDpi; // DebugLog.d(TAG, "densityDpi = " + mDensity); if (mDensity == 240) { webSettings.setDefaultZoom(ZoomDensity.FAR); } else if (mDensity == 160) { webSettings.setDefaultZoom(ZoomDensity.MEDIUM); } else if (mDensity == 120) { webSettings.setDefaultZoom(ZoomDensity.CLOSE); // }else if(mDensity == DisplayMetrics..DENSITY_XHIGH){ // webSettings.setDefaultZoom(ZoomDensity.FAR); } else if (mDensity == DisplayMetrics.DENSITY_HIGH) { webSettings.setDefaultZoom(ZoomDensity.FAR); } webView.setWebChromeClient(m_chromeClient);// (flash) dialogPress = new AlertDialog.Builder(this).setTitle("").setMessage(":0/0") .setPositiveButton("", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); } /** MemberVariables */ private WebChromeClient m_chromeClient = new WebChromeClient() { @Override public void onShowCustomView(View view, CustomViewCallback callback) { } @Override public void onCloseWindow(WebView window) { super.onCloseWindow(window); } @Override public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) { return super.onCreateWindow(view, dialog, userGesture, resultMsg); } /** * window.alerttitlefile://// */ public boolean onJsAlert(WebView view, String url, String message, JsResult result) { final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); builder.setTitle("").setIcon(R.drawable.qq_dialog_default_icon).setMessage(message) .setPositiveButton("", null); // // keycode84 builder.setOnKeyListener(new OnKeyListener() { public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // Log.v("onJsAlert", "keyCode==" + keyCode + "event=" + // event); return true; } }); // back builder.setCancelable(false); AlertDialog dialog = builder.create(); dialog.show(); result.confirm();// confirm, return true; // return super.onJsAlert(view, url, message, result); } public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) { return super.onJsBeforeUnload(view, url, message, result); } /** * window.confirmtitlefile://// */ public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); builder.setTitle("").setIcon(R.drawable.qq_dialog_default_icon).setMessage(message) .setPositiveButton("", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }).setNeutralButton("", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { result.cancel(); } }); // keycode84 builder.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { Log.v("onJsConfirm", "keyCode==" + keyCode + "event=" + event); return true; } }); // back // builder.setCancelable(false); AlertDialog dialog = builder.create(); dialog.show(); return true; // return super.onJsConfirm(view, url, message, result); } /** * window.prompttitlefile://// * window.prompt('', '618119.com'); */ public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) { final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); builder.setTitle("").setMessage(message); builder.setIcon(R.drawable.qq_dialog_default_icon); final EditText et = new EditText(view.getContext()); et.setSingleLine(); et.setText(defaultValue); builder.setView(et).setPositiveButton("", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(et.getText().toString()); } }).setNeutralButton("", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); // keycode84 builder.setOnKeyListener(new OnKeyListener() { public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { return true; } }); // back // builder.setCancelable(false); AlertDialog dialog = builder.create(); dialog.show(); return true; // return super.onJsPrompt(view, url, message, defaultValue, // result); } @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); } @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } @Override public void onRequestFocus(WebView view) { super.onRequestFocus(view); } /** * WebChromeClient */ public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); super.onGeolocationPermissionsShowPrompt(origin, callback); } }; /** * HelloWebViewClient * * @author Mars zhang * */ private class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // toast("shouldOverrideUrlLoading"+url,1); view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // view.setBackgroundColor(0); // toast("onPageStarted"+url,1); view.setVisibility(View.INVISIBLE); // imageView.setVisibility(View.VISIBLE); super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(final WebView view, String url) { // view.setBackgroundColor(0); // toast("onPageFinished"+url,1); view.setVisibility(View.VISIBLE); if (dialog != null) dialog.dismiss(); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // -2 toast("onPageFinished" + failingUrl, 1); if (dialog != null) dialog.dismiss(); view.clearView(); view.setVisibility(View.GONE); imageView.setVisibility(View.VISIBLE); // view.setVisibility(View.GONE); System.out.println(errorCode + " errorCode "); if (errorCode == -6) { try { view.stopLoading(); } catch (Exception e) { } try { view.clearView(); } catch (Exception e) { } if (view.canGoBack()) { view.goBack(); } } else if (errorCode == -2) { try { view.stopLoading(); view.destroy(); } catch (Exception e) { } try { view.clearView(); } catch (Exception e) { } if (view.canGoBack()) { view.goBack(); } } // Toast.makeText(And_meetActivity.this,errorCode+ // ""+description, Toast.LENGTH_SHORT).show(); Toast.makeText(WebdbActivity.this, "", Toast.LENGTH_SHORT).show(); // Toast.makeText(And_meetActivity.this, "", // Toast.LENGTH_LONG); } } // @Override // protected Dialog onCreateDialog(int id) { // if (id == PROGRESS_ID) { // return ProgressDialog.show(mContext, "", ".."); // } // return super.onCreateDialog(id); // } // @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if ((keyCode == KeyEvent.KEYCODE_BACK)) { // webView.goBack(); if (dialog != null) dialog.dismiss(); // finish(); return true; } return super.onKeyDown(keyCode, event); } /** * * * @param v */ public void message_post_web_tomain(View v) { AlertDialog.Builder builder1 = new AlertDialog.Builder(WebdbActivity.this); builder1.setTitle(""); builder1.setIcon(R.drawable.qq_dialog_default_icon);// builder1.setMessage(""); builder1.setPositiveButton("", new DialogInterface.OnClickListener() { // @Override public void onClick(DialogInterface dialog, int which) { if (null != webView) { webView.goBack(); finish(); } } }); builder1.setNegativeButton("", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder1.show(); } // /** * * 2014-7-225:18:50 MyWebViewDownLoadListener * * @author Mars zhang * */ private class MyWebViewDownLoadListener implements DownloadListener { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast t = Toast.makeText(mContext, "SD", Toast.LENGTH_LONG); t.setGravity(Gravity.CENTER, 0, 0); t.show(); return; } String fileName = ""; // toast(url,1); try { String test = URLDecoder.decode(url, "utf-8"); String s[] = Pattern.compile("=").split(test); fileName = s[s.length - 1]; System.out.println(test); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } downLoadFile(url, fileName); // downLoadApk(url); // FinalHttp fh = new FinalHttp(); // //download // HttpHandler handler = // fh.download("http://www.xxx.com//xxx.apk", // // "/mnt/sdcard/testapk.apk", // // new AjaxCallBack() { // @Override // public void onLoading(long count, long current) { // System.out.println(""+current+"/"+count); // } // // public void onSuccess(File t) { // textView.setText(t==null?"null":t.getAbsoluteFile().toString()); // } // }); // //stop() // handler.stop(); // System.out.println(url); // DownloaderTask task = new DownloaderTask(); // task.execute(url); } } /** */ private void downLoadFile(String url, String fileName) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// SD FinalHttp fh = new FinalHttp(); dialogPress.show(); // File clear_temp = new File(Environment.getExternalStorageDirectory(), fileName); deleteFile(clear_temp); // download HttpHandler handler1 = fh.download(url, // clear_temp.getAbsolutePath(), // // Environment.getExternalStorageDirectory().getAbsolutePath() true, // true: // false: new AjaxCallBack<File>() { @Override public void onLoading(long count, long current) {// System.out.println(current + "/" + count); dialogPress.setMessage(":" + current / 1024 + "k/" + count / 1024 + "k"); super.onLoading(count, current); } @Override public void onFailure(Throwable t, int errorNo, String strMsg) { if (null != dialogPress) { dialogPress.dismiss(); } toast("", 0); super.onFailure(t, errorNo, strMsg); } @Override public void onSuccess(File t) { if (null != dialogPress) { dialogPress.dismiss(); } toast(t == null ? "null" : t.getAbsoluteFile().toString() + "", 1); } }); } else { toast("SD", 0); } } /** */ private void downLoadApk(String url) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// SD FinalHttp fh = new FinalHttp(); // HttpClient client=fh.getHttpClient(); // client.getParams().setIntParameter("http.socket.timeout",10000); // File clear_temp = new File(Environment.getExternalStorageDirectory(), "temp.pdf"); deleteFile(clear_temp); File temp = new File(Environment.getExternalStorageDirectory(), "temp.pdf"); dialogPress.show(); // download HttpHandler handler1 = fh.download(url, // // temp.getAbsolutePath(), // Environment.getExternalStorageDirectory().getAbsolutePath(), false, // true: // false: new AjaxCallBack<File>() { @Override public void onLoading(long count, long current) {// System.out.println(current + "/" + count); dialogPress.setMessage(":" + current / 1024 + "k/" + count / 1024 + "k"); super.onLoading(count, current); } @Override public void onFailure(Throwable t, int errorNo, String strMsg) { dialogPress.dismiss(); super.onFailure(t, errorNo, strMsg); } @Override public void onSuccess(File t) { System.out.println(t == null ? "null" : t.getAbsoluteFile().toString() + ""); dialogPress.dismiss(); } }); } else { toast("SD", 1); } } /** */ private void toast(String strMsg, int L1S0) { Toast.makeText(getApplicationContext(), strMsg, L1S0).show(); } /** */ public void deleteFile(File file) { if (file.exists()) { // if (file.isFile()) { // file.delete(); // delete() ; System.out.println("file.delete();"); } else if (file.isDirectory()) { // File files[] = file.listFiles(); // files[]; for (int i = 0; i < files.length; i++) { // this.deleteFile(files[i]); // } } file.delete(); System.out.println("file.delete();"); } else { System.out.println(""); } } // /** * * 2014-7-225:18:40 DownloaderTask * * @author Mars zhang * */ private class DownloaderTask extends AsyncTask<String, Void, String> { public DownloaderTask() { } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub String url = params[0]; // Log.i("tag", "url="+url); String fileName = url.substring(url.lastIndexOf("/") + 1); fileName = URLDecoder.decode(fileName); Log.i("tag", "fileName=" + fileName); File directory = Environment.getExternalStorageDirectory(); File file = new File(directory, fileName); if (file.exists()) { Log.i("tag", "The file has already exists."); return fileName; } try { HttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter("http.socket.timeout", 10000);// HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { HttpEntity entity = response.getEntity(); InputStream input = entity.getContent(); writeToSDCard(fileName, input); input.close(); // entity.consumeContent(); return fileName; } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } @Override protected void onCancelled() { // TODO Auto-generated method stub super.onCancelled(); } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); closeProgressDialog(); if (result == null) { Toast t = Toast.makeText(mContext, "", Toast.LENGTH_LONG); t.setGravity(Gravity.CENTER, 0, 0); t.show(); return; } Toast t = Toast.makeText(mContext, "SD", Toast.LENGTH_LONG); t.setGravity(Gravity.CENTER, 0, 0); t.show(); File directory = Environment.getExternalStorageDirectory(); File file = new File(directory, result); Log.i("tag", "Path=" + file.getAbsolutePath()); Intent intent = getFileIntent(file); startActivity(intent); } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); showProgressDialog(); } @Override protected void onProgressUpdate(Void... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); } } /** MemberVariables */ private ProgressDialog mDialog; private void showProgressDialog() { if (mDialog == null) { mDialog = new ProgressDialog(mContext); mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// mDialog.setMessage(" ..."); mDialog.setIndeterminate(false);// mDialog.setCancelable(true);// mDialog.setCanceledOnTouchOutside(false); mDialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { // TODO Auto-generated method stub mDialog = null; } }); mDialog.show(); } } private void closeProgressDialog() { if (mDialog != null) { mDialog.dismiss(); mDialog = null; } } public Intent getFileIntent(File file) { // Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf"); Uri uri = Uri.fromFile(file); String type = getMIMEType(file); Log.i("tag", "type=" + type); Intent intent = new Intent("android.intent.action.VIEW"); intent.addCategory("android.intent.category.DEFAULT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(uri, type); return intent; } public void writeToSDCard(String fileName, InputStream input) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File directory = Environment.getExternalStorageDirectory(); File file = new File(directory, fileName); // if(file.exists()){ // Log.i("tag", "The file has already exists."); // return; // } try { FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[2048]; int j = 0; while ((j = input.read(b)) != -1) { fos.write(b, 0, j); } fos.flush(); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Log.i("tag", "NO SDCard."); } } private String getMIMEType(File f) { String type = ""; String fName = f.getName(); /* */ String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase(); /* MimeType */ if (end.equals("pdf")) { type = "application/pdf";// } else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) { type = "audio/*"; } else if (end.equals("3gp") || end.equals("mp4")) { type = "video/*"; } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) { type = "image/*"; } else if (end.equals("apk")) { /* android.permission.INSTALL_PACKAGES */ type = "application/vnd.android.package-archive"; } // else if(end.equals("pptx")||end.equals("ppt")){ // type = "application/vnd.ms-powerpoint"; // }else if(end.equals("docx")||end.equals("doc")){ // type = "application/vnd.ms-word"; // }else if(end.equals("xlsx")||end.equals("xls")){ // type = "application/vnd.ms-excel"; // } else { // /* */ type = "*/*"; } return type; } }