Html5 webview 模版 ,实现 JS 获取imei , 上传文件功能

package com.shengjing.apk;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

	private WebView webview;
	protected Uri mCameraUri;

	public static final int FILECHOOSER_RESULTCODE = 120;
	private static final int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 121;

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

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取webView 控件
		webview = (WebView) findViewById(R.id.webview);
		// 加上这句话才能使用javascript方法
		webview.getSettings().setJavaScriptEnabled(true);
		webview.loadUrl("http://124.133.16.116:800/index.php");
		// webview.loadUrl("file:///android_asset/demo.html");
		// 增加接口方法,让html页面调用
		webview.addJavascriptInterface(this, "apkcontext");
		webview.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onGeolocationPermissionsHidePrompt() {
				super.onGeolocationPermissionsHidePrompt();
				Log.i(" ----------- ", "onGeolocationPermissionsHidePrompt");
			}

			@Override
			public void onGeolocationPermissionsShowPrompt(final String origin,
					final GeolocationPermissions.Callback callback) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);
				builder.setMessage("共享您的位置信息?");
				OnClickListener dialogButtonOnClickListener = new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int clickedButton) {
						if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
							callback.invoke(origin, true, true);
						} else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
							callback.invoke(origin, false, false);
						}
					}
				};
				builder.setPositiveButton("同意", dialogButtonOnClickListener);
				builder.setNegativeButton("拒绝", dialogButtonOnClickListener);
				builder.show();
				super.onGeolocationPermissionsShowPrompt(origin, callback);
				Log.i("--------", "onGeolocationPermissionsShowPrompt");
			}

			// 扩展支持alert事件
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				AlertDialog.Builder builder = new AlertDialog.Builder(view
						.getContext());
				builder.setTitle("提示").setMessage(message)
						.setPositiveButton("确定", null);
				builder.setCancelable(false);
				// builder.setIcon(R.drawable.icon);
				AlertDialog dialog = builder.create();
				dialog.show();
				result.confirm();
				return true;
			}

			// 扩展浏览器上传文件
			// 3.0++版本
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType) {
				openFileChooserImpl(uploadMsg);
			}

			// 3.0--版本
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				openFileChooserImpl(uploadMsg);
			}

			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType, String capture) {
				openFileChooserImpl(uploadMsg);
			}

			// For Android > 5.0
			public boolean onShowFileChooser(WebView webView,
					ValueCallback<Uri[]> uploadMsg,
					WebChromeClient.FileChooserParams fileChooserParams) {
				openFileChooserImplForAndroid5(uploadMsg);
				return true;
			}
		});
		webview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url)

			{ // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边

				view.loadUrl(url);

				return true;

			}

		});
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
			webview.goBack();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			ConfirmExit();// 按了返回键,但已经不能返回,则执行退出确认
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void ConfirmExit() {// 退出确认
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setTitle("确认");
		ad.setMessage("是否退出?");
		ad.setPositiveButton("是", new DialogInterface.OnClickListener() {// 退出按钮
					@Override
					public void onClick(DialogInterface dialog, int i) {
						// TODO Auto-generated method stub
						MainActivity.this.finish();// 关闭activity

					}
				});
		ad.setNegativeButton("否", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int i) {
				// 不退出不用执行任何操作
			}
		});
		ad.show();// 显示对话框
	}

	public String getIMEI() {
		String imei = ((TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		return imei;
	}

	private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
		mUploadMessage = uploadMsg;
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		startActivityForResult(addCameraIntent(intent), FILECHOOSER_RESULTCODE);
	}

	private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
		mUploadMessageForAndroid5 = uploadMsg;
		Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
		contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
		contentSelectionIntent.setType("image/*");
		startActivityForResult(addCameraIntent(contentSelectionIntent),
				FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
	}

	private Intent addCameraIntent(Intent intent) {
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		this.mCameraUri = createCameraUri();
		cameraIntent.putExtra("output", this.mCameraUri);
		cameraIntent.addCategory(Intent.CATEGORY_DEFAULT);

		Intent chooserIntent = Intent.createChooser(intent, "选择要上传的文件");
		chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
				new Intent[] { cameraIntent });
		return chooserIntent;
	}

	protected Uri createCameraUri() {
		File localFile = new File(Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
				.getAbsolutePath()
				+ File.separator + "browser-photos");
		localFile.mkdirs();
		return Uri.fromFile(new File(localFile.getAbsolutePath()
				+ File.separator + System.currentTimeMillis() + ".jpg"));
	}

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

		} else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
			if (null == mUploadMessageForAndroid5)
				return;
			Uri result = (intent == null || resultCode != RESULT_OK) ? null
					: intent.getData();
			if (result != null) {
				mUploadMessageForAndroid5.onReceiveValue(new Uri[] { result });
			} else {
				mUploadMessageForAndroid5
						.onReceiveValue(new Uri[] { mCameraUri });
			}
			mUploadMessageForAndroid5 = null;
			mCameraUri = null;

		}
	}

}

地址

http://git.oschina.net/sfshine/WebviewH5

转载于:https://my.oschina.net/sfshine/blog/708000

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值