文章标签 ‘源代码’
201212 月11

JS源码:网页滚动右下角出现返回顶部goTop

效果如图:

直接贴代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <HEAD>
  <TITLE> Wizzer.cn </TITLE>
  <style type="text/css" media="screen">
#goTop {position:fixed;right:20px;bottom:20px;width:40px;height:32px;padding:8px 0 0;background-color:#69c;border-radius:6px;cursor:pointer;}
#goTop:hover {background-color:#369;}
#goTop:hover .gotop1 {border-left:12px solid #369;border-right:12px solid #369;}
#goTop .gotop1 {width:0;margin:0 auto;border-bottom:12px solid #FFF;border-left:12px solid #69c;border-right:12px solid #69c;}
#goTop .gotop2 {width:10px;height:10px;margin:0 auto;background-color:#FFF;}
</style>
 </HEAD>

 <BODY>

a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>

<div title="返回顶部" id="goTop" style="display:none;">
	<div class="gotop1"></div>
	<div class="gotop2"></div>
</div>

<script type="text/javascript">
	    function $getId(Id) {
	        return document.getElementById(Id);
	    }
	    var goTop = $getId("goTop");
	    window.onscroll = function () {
	        if (document.documentElement.scrollTop + document.body.scrollTop > 350) {
	            goTop.style.display = "";
	        } else {
	            goTop.style.display = "none";
	        }
	    }
	    goTop.onclick = function () {
	        var Timer = setInterval(GoTop, 10);
	        function GoTop() {
	            if (document.documentElement.scrollTop + document.body.scrollTop < 1) {
	                clearInterval(Timer);
	            } else {
	                document.documentElement.scrollTop /= 1.1;
	                document.body.scrollTop /= 1.1;
	            }
	        }
	    }
	</script>
 </BODY>
</HTML>

 

 

201211 月22

经验分享:Firefox插件开发说明

Firefox插件分为两种,即extension和plugin,网上搜索到的示例多是 XUL应用程序开发,XUL插件安装后需要重启浏览器才能使用,而这篇文章主要介绍如何使用 Add-on 来开发JS+HTML+CSS 应用,如Chrome插件可直接安装使用。

(感兴趣的朋友可以查看本站上一篇文章:chrome插件开发说明,对比一下你会发现chrome插件开发简直太easy – -)

言归正传,Add-on 提供SDK下载和在线开发两种方式,访问 https://builder.addons.mozilla.org/ 通过简单的注册,点击“Create an Add-on Now”,自动生成一个带main.js 的项目,如下图所示,你可以在Data文件夹下上传编辑自己的文件(若上传文件后左侧半天不出来按下F5即可):

Add-on 启动函数为 main.js,这里可以通过 require 申请一些资源权限,而放置在Data用户文件夹里的JS是不能直接使用 require 的,可能是Add-on 框架设计本身就不支持随意的调用系统资源吧,这个时候就得利用 port.on 和 port.emit 来传递变量和执行方法。

网络请求的示例可以访问:https://builder.addons.mozilla.org/package/89576/ 来查看,里面具体介绍了 port.on 和 port.emit 的使用、panel的生成、jQuery的引入、网络请求等,这个例子非常好。

通过查看其他网友分享的代码学习,地址:https://builder.addons.mozilla.org/search/ 输入关键词,查找你关心想实现的功能吧。

 

具体功能开发不在累述,我写的这个简单查询功能的插件在商城里搜索“合肥公积金查询”即可下载,下载后若你是win7系统,则:

C:\Users\Wizzer\AppData\Roaming\Mozilla\Firefox\Profiles\zah0wctd.default\extensions

找到 wizzer.cn@gmail.com.xpi  解压即可,源代码没加密,给大家做学习参考之用。

 

其他:

打包:在根文件夹选择所有文件,压缩成zip文件,改后缀名为 xpi。

安装:把xpi文件拖到firefox浏览器中即可。

调试:ctrl—shfit—j 调试插件。

 

扩展组件在线安装地址:

https://addons.mozilla.org/zh-CN/firefox/addon/%E5%90%88%E8%82%A5%E5%85%AC%E7%A7%AF%E9%87%91%E6%9F%A5%E8%AF%A2/

 

201211 月20

经验分享:Chrome插件开发源码说明

Chrome插件开发极其简单,只要会JS+HTML+CSS即可,当然我捣鼓的是简单的应用作为学习和验证之用,没有更多的深入。

本示例采用 jQuery 实现用户登录查询公积金余额功能,接口提供的功能较多但作为学习么,只开发了一个查询余额的功能。

运行效果:

1、首先创建文件夹,文档结构如下:

2、编辑manifest.json文件,填写应用信息、访问权限等:

{ 
  "name": "合肥公积金查询",
  "version": "2012.11.20.0",
  "manifest_version": 2,
  "description": "这是一款合肥市住房公积金查询工具,用于学习测试仅提供余额查询。@Wizzer",
  "icons":{"16":"16.png","48":"48.png"},
  "content_scripts":[{
      "js": [ "scripts/lib/jquery-1.7.2.min.js","scripts/main.js"],
      "matches": [ "http://*/*", "https://*/*" ] 
   }],
  "browser_action": {
	"default_icon": "16.png",
	"default_popup": "index.html"
  },
  "homepage_url":"",
  "permissions": [ "cookies", "tabs", "http://*/*", "https://*/*" ]

}

注意事项:

A、目前最新版的chrome要求设置  “manifest_version”: 2 ;

B、permissions 配置了cookies权限,因为在应用中加入了记住密码功能;

C、API要求JS不可以内联,就是不能直接在页面元素上写JS,例如点击按钮alert提示都不会执行的;

3、本着JS和HTML分离的原则,编写  main.js 文件:

var url = "/chrome";
var key = "接口APP_KEY隐藏";
var zgyhzh="";
var dwyhzh="";
var uptime="";
var hm="";
var mm="";
if (!chrome.cookies) {
  chrome.cookies = chrome.experimental.cookies;
}
function delCookie(name) {
  chrome.cookies.remove({"name": name,"url":url});
}

function setCookie(name,value) {
  chrome.cookies.set({"name": name,"value":value,"url":url ,"expirationDate":1392000000});
}

function initCookie() {
  var str="";
  chrome.cookies.get({"name": "hm","url":url },function(cookie){
        str=cookie.value; 
		if(""!=str){
			$('#savehm').attr("checked",true);
			$('#hm').val(Base64.decode(str));
		}
  });
  chrome.cookies.get({"name": "mm","url":url },function(cookie){
		str=cookie.value; 
		if(""!=str){
			$('#savemm').attr("checked",true);
			$('#mm').val(Base64.decode(str));
		}
  });
}

function login(){
	 hm=Base64.encode($('#hm').val());
	 mm=Base64.encode($('#mm').val());

	$.ajax({
        			url : "http://220.178.98.86/hfgjj/service/login.jsp",
        			data : {"hm":hm,"mm":mm,"app_key":key} ,
        			success : function (res) {
						loginData(res);
						return false;
        			},
        			fail : function(res) {
        				loginData(res);
        			}
        		});

}

function loginData(res){
	if(res.indexOf("error")>=0){
	    var obj = jQuery.parseJSON(res);
		if(""!=obj.tip){
			$("#tip").html("<HR><span style='color:red'>"+obj.tip+"</span>");

		}
	}else if(res.indexOf("more")>=0){
		var obj = jQuery.parseJSON(res);
		if("false"==obj.more){
			zgyhzh=obj.zgyhzh;
			dwyhzh=obj.dwyhzh;
			uptime=obj.uptime;
			oneData();

		}else if("true"==obj.more){
			uptime=obj.uptime;
			var zgyhzhlist=obj.zgyhzhlist;
			$.each(zgyhzhlist,function(entryIndex,entry){ 
				if("true"==entry.zt){
					zgyhzh=entry.zgyhzh;
					dwyhzh=entry.dwyhzh;
					oneData();
					$("#note")[0].style.display='block';
					return;

				}
                });     
		}

	}else{

		$("#tip").html("<HR><span style='color:red'>"+res+"</span>");
	}

}
function oneData(){

			var z=Base64.encode(zgyhzh);
			var d=Base64.encode(dwyhzh);
			$.ajax({
        			url : "http://220.178.98.86/hfgjj/service/grindex.jsp",
        			data : {"hm":hm,"mm":mm,"app_key":key,"zgyhzh":z,"dwyhzh":d} ,
        			success : function (res) {
						showData(res);
						return false;
        			},
        			fail : function(res) {

        			}
        		});

}

function showData(res){
	if(res.indexOf("error")>=0){
	    var obj = jQuery.parseJSON(res);
		if(""!=obj.tip){
			$("#tip").html("<HR><span style='color:red'>"+obj.tip+"</span>");

		}
	}else{
			$("#T1")[0].style.display='none'; 
			$("#T2")[0].style.display='block';
	var obj = jQuery.parseJSON(res);
	var scje=obj.scje;

	$("#uptime").html("<span style='color:red'>"+uptime+"</span>");
	$("#yue").html("<span style='color:red'>"+scje+"</span>");
	}
}

function init(){
  initCookie();
  $('#bt').click(function() {
	  if($('#savemm').attr('checked')){
		 setCookie("mm",Base64.encode($('#mm').val()));
		 setCookie("hm",Base64.encode($('#hm').val()));
	  }else if($('#savehm').attr('checked')){
		 setCookie("mm","");
		 setCookie("hm",Base64.encode($('#hm').val()));
	  }else{
		 setCookie("mm","");
		 setCookie("hm","");
	  }
	  $("#tip").html("<HR><span style='color:red'>Loading...</span>");
	  login();

  });

  $('#savemm').click(function() {
	 if($('#savemm').attr('checked')){
		$('#savehm').attr("checked",true);
	 }else{
		$('#savehm').attr("checked",false);
	 }
  });
}

document.addEventListener('DOMContentLoaded', function () {
  init();
});

PS:搞开发的JS都能看懂,就不注释了。。。

4、index.html 页面的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>合肥市住房公积金查询</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<meta http-equiv="Cache-Control" content="no-cache"/><!-- 公共样式 -->
<script type='text/javascript' src='scripts/lib/jquery-1.7.2.min.js'></script>
<script type='text/javascript' src='scripts/lib/Base64.js'></script>
<script type='text/javascript' src='scripts/main.js'></script> 

<STYLE type=text/css>BODY {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
DIV {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
P {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
EM {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
SPAN {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
A {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
TD {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
FORM {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
BUTTON {
	PADDING-BOTTOM: 0px; LINE-HEIGHT: 1.5em; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; WORD-WRAP: break-word; FONT-SIZE: 12px; WORD-BREAK: break-all; PADDING-TOP: 0px
}
body {COLOR: #333 ;min-width: 220px; margin: 0; font: 12px "Helvetica Neue", Helvetica, Arial, sans-serif; width: auto}

EM {
	FONT-WEIGHT: bold
}
STRONG {
	FONT-WEIGHT: bold
}
DEL {
	TEXT-DECORATION: line-through
}
INPUT {
	MARGIN: 2px 0px; FONT-SIZE: 12px
}
SELECT {
	MARGIN: 2px 0px; FONT-SIZE: 12px
}
IMG {
	BORDER-BOTTOM: medium none; BORDER-LEFT: medium none; BORDER-TOP: medium none; BORDER-RIGHT: medium none
}
HR {
	BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; HEIGHT: 0px; CLEAR: both; BORDER-TOP: #ddd 1px solid; BORDER-RIGHT: 0px
}
A:link {
	COLOR: #36c; TEXT-DECORATION: underline
}
A:visited {
	COLOR: #36c; TEXT-DECORATION: underline
}
A.im {
	COLOR: #f60
}
.im {
	COLOR: #f60
}
.imp {
	COLOR: #f00
}
.gp {
	COLOR: #06c
}
.mp {
	COLOR: #f90
}
.module {
	PADDING-BOTTOM: 0px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; PADDING-TOP: 0px
}
.wrapper {

}
.none {
	DISPLAY: none
}
.header {
	BORDER-BOTTOM: #d2d2d2 1px solid; PADDING-BOTTOM: 2px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; BACKGROUND: #f5f5f5; PADDING-TOP: 2px
}
.footer {
	PADDING-BOTTOM: 2px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; BORDER-TOP: #d2d2d2 1px solid; PADDING-TOP: 2px
}
.logo {
	PADDING-BOTTOM: 0px; PADDING-LEFT: 1px; PADDING-RIGHT: 1px; PADDING-TOP: 2px
}
.logo A {
	FONT-SIZE: 14px; TEXT-DECORATION: none
}
.nav {
	PADDING-BOTTOM: 5px; PADDING-LEFT: 5px; PADDING-RIGHT: 5px; PADDING-TOP: 5px
}
.cl {

}
.module {
	MARGIN-TOP: 3px
}
.gtt {
	TEXT-ALIGN: center
}
.capt {
	VERTICAL-ALIGN: middle
}
.err {
	BACKGROUND: #fc9
}
.ptit {
	COLOR: #000; FONT-SIZE: 14px
}
</STYLE>
<BODY> 
<DIV class=wrapper id=top>
<DIV class=logo><A href="http://220.178.98.86/hfgjj/jsp/web/public/search/grlogin.jsp" target="_blank"><IMG alt="合肥市住房公积金中心" 
src="sjimg/logo.jpg"></A></DIV>
<DIV  ID="T1">
<DIV class="tit module"><STRONG>个人公积金查询</STRONG></DIV> 
<DIV class=module>身份证号码<BR>
<INPUT id="hm" maxLength="18" type="text" 
name="hm"> <input id="savehm" name="savehm" type="checkbox"> 记住号码
<BR>密码<BR>
<INPUT id="mm" maxLength="6" type="password" 
name="mm"> <input id="savemm" name="savemm" type="checkbox"> 记住密码
<div id="tip"></div>
<HR>
<INPUT id="bt" class="bts" value="登 录" type="button">
</DIV>
</DIV>
<DIV  ID="T2" style="display:none">
<DIV class="tit module"><STRONG>公积金余额</STRONG></DIV>

截至:<div id="uptime"></div>
您的公积金账户余额为:<div id="yue"></div>
<div id="note" style="display:none">您有多个帐号,本工具只显示您正常缴费的公积金帐号余额。</div>

</DIV>

<DIV class=footer><A href="index.html">返回首页</A>  <BR>Copyright @Wizzer</DIV>

</DIV>

</BODY></HTML>

5、调试部署:

菜单–工具–扩展程序–载入正在开发的扩展程序,右上角会出现16*16的图标,o(∩_∩)o 哈哈

6、将应用发布到google网上应用商城:

首次发布项目之前,您必须支付 US$5.00的一次性开发者注册费。我们收取此费用的目的是对开发者帐户进行验证,并为用户提供更好的保护,以防他们受到欺骗性活动的侵害。 支付注册费后,您就可以发布任意数量的项目,且无需再支付注册费了。

首先你需要有一张VISA信用卡,登陆google电子钱包注册信用卡。

https://www.google.com/checkout/   –注意要加https哦,你懂得

这里要注意的是,自动弹出的第一张信用卡注册界面不是如上的,很可能支付不成功,这个时候进入“支付方式”,选择修改信用卡,出现上面的界面选择New York 输入正确的邮编才能支付成功。

进入开发者中心(扩展程序最下面点击“获取更多扩展程序”,进入网上应用商城)

在开发者中心修改用户偏好设置,勾选“为我在 Chrome 网上应用店中的所有应用启用用户反馈功能。”,否则点击“立即支付注册费”会没反应(实在没辙换成IE试试吧)。

支付成功后耐心等待吧,我正在等待订单审核ing……

7、发布应用:

开发者中心点击添加新项目,把项目文件夹打包为zip压缩包上传即可。其他略,都能看懂。。

8、关于firewall:

以上许多操作,你会发现一会这个网页打不开,那个网页等白天没反应,这个时候你就需要用chrome插件“SwitchySharp”了,具体怎么用百度一下吧,步骤也很多很麻烦,关键是耐心按教程来。

chrome里可以用 SwitchySharp,那么IE里要用怎么办,在IE里手动设置下代理即可,端口号到 SwitchySharp 选项里查看。

可移步:http://www.delver.net/?p=267  看教程~~

9、其他

等订单审核完毕应用发布后,大家就可以在chrome 商城里搜索“合肥公积金查询”,那就是我写的这个应用了,如果你是win7系统的话,可以在:

C:\Users\Wizzer\AppData\Local\Google\Chrome\User Data\Default\Extensions

文件夹下看到源代码。over~~

几点思考,chrome插件是js+html+CSS的网页应用,不能直接执行JSP、ASP、PHP什么的,实现功能都需要调用chrome的接口、你自己应用提供的接口,那么可以不可以使用iframe嵌入自己的应用呢(- -)。

另外就是session传递的问题,从一个页面到另外一页面,信息怎么传递,用cookies感觉不太合适,也不能把所有的逻辑写在一个页面啊,这个需要深入的去研究。

再之就是js不能内联,那么实现一些功能就比较麻烦了,比如动态创建可点击的按钮,现在还没想到什么好办法,相信深入研究是可以解决的,JS要相当的熟才行啊,偶么就一般般。- –

20128 月29

Lucene 3.6.1:中文分词、创建索引库、排序、多字段分页查询以及高亮显示源码

1、准备工作

下载lucene 3.6.1 : http://lucene.apache.org/

下载中文分词IK Analyzer: http://code.google.com/p/ik-analyzer/downloads/list (注意下载的是IK Analyzer 2012_u5_source.zip,其他版本有bug)

下载solr 3.6.1:  http://lucene.apache.org/solr/(编译IK Analyzer时需引用包)

OK,将lucene 、solr 相关包(lucene-core-3.6.1.jar、lucene-highlighter-3.6.1.jar、lucene-analyzers-3.6.1.jar、apache-solr-core-3.6.1.jar、apache-solr-solrj-3.6.1.jar)拷贝到项目lib下,IK源码置于项目src下。

2、从Oracle数据库中取数据创建索引(使用IK分词)

package lucene.util;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.util.Version;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.sql.Connection;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import modules.gk.Gk_info;
import modules.gk.Gk_infoSub;
import web.sys.Globals;
import web.db.DBConnector;
import web.db.ObjectCtl;
import web.util.StringUtil;
//Wizzer.cn
public class LuceneIndex {
    IndexWriter writer = null;
    FSDirectory dir = null;
    boolean create = true;//是否初始化&覆盖索引库

    public void init() {
        long a1 = System.currentTimeMillis();
        System.out.println("[Lucene 开始执行:" + new Date() + "]");
        Connection con = DBConnector.getconecttion(); //取得一个数据库连接
        try {
            final File docDir = new File(Globals.SYS_COM_CONFIG.get("sys.index.path").toString());//E:\lucene
            if (!docDir.exists()) {
                docDir.mkdirs();
            }
            String cr = Globals.SYS_COM_CONFIG.get("sys.index.create").toString();//true or false
            if ("false".equals(cr.toLowerCase())) {
                create = false;
            }
            dir = FSDirectory.open(docDir);
//            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
            Analyzer analyzer = new IKAnalyzer(true);
            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36, analyzer);
            if (create) {
                // Create a new index in the directory, removing any
                // previously indexed documents:
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            } else {
                // Add new documents to an existing index:
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
            }
            writer = new IndexWriter(dir, iwc);
            String sql = "SELECT indexno,title,describes,pdate,keywords FROM TABLEA WHERE STATE=1 AND SSTAG<>1 ";
            int rowCount = ObjectCtl.getRowCount(con, sql);
            int pageSize = StringUtil.StringToInt(Globals.SYS_COM_CONFIG.get("sys.index.size").toString());   //每页记录数
            int pages = (rowCount - 1) / pageSize + 1; //计算总页数
            ArrayList list = null;
            Gk_infoSub gk = null;
            for (int i = 1; i < pages+1; i++) {
                long a = System.currentTimeMillis();
                list = ObjectCtl.listPage(con, sql, i, pageSize, new Gk_infoSub());
                for (int j = 0; j < list.size(); j++) {
                    gk = (Gk_infoSub) list.get(j);
                    Document doc = new Document();
                    doc.add(new Field("indexno", StringUtil.null2String(gk.getIndexno()), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));//主键不分词
                    doc.add(new Field("title", StringUtil.null2String(gk.getTitle()), Field.Store.YES, Field.Index.ANALYZED));
                    doc.add(new Field("describes", StringUtil.null2String(gk.getDescribes()), Field.Store.YES, Field.Index.ANALYZED));
                    doc.add(new Field("pdate", StringUtil.null2String(gk.getPdate()), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));//日期不分词
                    doc.add(new Field("keywords", StringUtil.null2String(gk.getKeywords()), Field.Store.YES, Field.Index.ANALYZED));
                    writer.addDocument(doc);
                    ObjectCtl.executeUpdateBySql(con,"UPDATE TABLEA SET SSTAG=1 WHERE indexno='"+gk.getIndexno()+"'");//更新已索引状态
                }

                long b = System.currentTimeMillis();
                long c = b - a;
                System.out.println("[Lucene " + rowCount + "条," + pages + "页,第" + i + "页花费时间:" + c + "毫秒]");
            }
            writer.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBConnector.freecon(con); //释放数据库连接
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (CorruptIndexException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (dir != null && IndexWriter.isLocked(dir)) {
                        IndexWriter.unlock(dir);//注意解锁
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long b1 = System.currentTimeMillis();
        long c1 = b1 - a1;
        System.out.println("[Lucene 执行完毕,花费时间:" + c1 + "毫秒,完成时间:" + new Date() + "]");
    }
}

 

3、单字段查询以及多字段分页查询高亮显示

 

package lucene.util;

import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.Version;
import modules.gk.Gk_infoSub;

import java.util.ArrayList;
import java.io.File;
import java.io.StringReader;
import java.lang.reflect.Constructor;

import web.util.StringUtil;
import web.sys.Globals;
import org.wltea.analyzer.lucene.IKAnalyzer;
//Wizzer.cn
public class LuceneQuery {
    private static String indexPath;// 索引生成的目录
    private int rowCount;// 记录数
    private int pages;// 总页数
    private int currentPage;// 当前页数
    private int pageSize;   //每页记录数

    public LuceneQuery() {
        this.indexPath = Globals.SYS_COM_CONFIG.get("sys.index.path").toString();
    }

    public int getRowCount() {
        return rowCount;
    }

    public int getPages() {
        return pages;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    /**
     * 函数功能:根据字段查询索引
     */
    public ArrayList queryIndexTitle(String keyWord, int curpage, int pageSize) {
        ArrayList list = new ArrayList();
        try {
            if (curpage <= 0) {
                curpage = 1;
            }
            if (pageSize <= 0) {
                pageSize = 20;
            }
            this.pageSize = pageSize;   //每页记录数
            this.currentPage = curpage;   //当前页
            int start = (curpage - 1) * pageSize;
            Directory dir = FSDirectory.open(new File(indexPath));
            IndexReader reader = IndexReader.open(dir);
            IndexSearcher searcher = new IndexSearcher(reader);
            Analyzer analyzer = new IKAnalyzer(true);
            QueryParser queryParser = new QueryParser(Version.LUCENE_36, "title", analyzer);
            queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
            Query query = queryParser.parse(keyWord);
            int hm = start + pageSize;
            TopScoreDocCollector res = TopScoreDocCollector.create(hm, false);
            searcher.search(query, res);

            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
            this.rowCount = res.getTotalHits();
            this.pages = (rowCount - 1) / pageSize + 1; //计算总页数
            TopDocs tds = res.topDocs(start, pageSize);
            ScoreDoc[] sd = tds.scoreDocs;
            for (int i = 0; i < sd.length; i++) {
                Document hitDoc = reader.document(sd[i].doc);
                list.add(createObj(hitDoc, analyzer, highlighter));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;

    }
    /**
     * 函数功能:根据字段查询索引
     */
    public ArrayList queryIndexFields(String allkeyword, String onekeyword, String nokeyword, int curpage, int pageSize) {
        ArrayList list = new ArrayList();
        try {
            if (curpage <= 0) {
                curpage = 1;
            }
            if (pageSize <= 0) {
                pageSize = 20;
            }
            this.pageSize = pageSize;   //每页记录数
            this.currentPage = curpage;   //当前页
            int start = (curpage - 1) * pageSize;
            Directory dir = FSDirectory.open(new File(indexPath));
            IndexReader reader = IndexReader.open(dir);
            IndexSearcher searcher = new IndexSearcher(reader);
            BooleanQuery bQuery = new BooleanQuery();  //组合查询
            if (!"".equals(allkeyword)) {//包含全部关键词
                KeywordAnalyzer analyzer = new KeywordAnalyzer();
                BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};//AND
                Query query = MultiFieldQueryParser.parse(Version.LUCENE_36, allkeyword, new String[]{"title", "describes", "keywords"}, flags, analyzer);
                bQuery.add(query, BooleanClause.Occur.MUST);  //AND
            }
            if (!"".equals(onekeyword)) { //包含任意关键词
                Analyzer analyzer = new IKAnalyzer(true);
                BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};//OR
                Query query = MultiFieldQueryParser.parse(Version.LUCENE_36, onekeyword, new String[]{"title", "describes", "keywords"}, flags, analyzer);
                bQuery.add(query, BooleanClause.Occur.MUST);  //AND
            }
            if (!"".equals(nokeyword)) { //排除关键词
                Analyzer analyzer = new IKAnalyzer(true);
                BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};//NOT
                Query query = MultiFieldQueryParser.parse(Version.LUCENE_36, nokeyword, new String[]{"title", "describes", "keywords"}, flags, analyzer);
                bQuery.add(query, BooleanClause.Occur.MUST_NOT);  //AND

            }
            int hm = start + pageSize;
            TopScoreDocCollector res = TopScoreDocCollector.create(hm, false);
            searcher.search(bQuery, res);
            SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
            Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(bQuery));
            this.rowCount = res.getTotalHits();
            this.pages = (rowCount - 1) / pageSize + 1; //计算总页数
            System.out.println("rowCount:" + rowCount);
            TopDocs tds = res.topDocs(start, pageSize);
            ScoreDoc[] sd = tds.scoreDocs;
            Analyzer analyzer = new IKAnalyzer();
            for (int i = 0; i < sd.length; i++) {
                Document hitDoc = reader.document(sd[i].doc);
                list.add(createObj(hitDoc, analyzer, highlighter));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;

    }

    /**
     * 创建返回对象(高亮)
     */

    private synchronized static Object createObj(Document doc, Analyzer analyzer, Highlighter highlighter) {

        Gk_infoSub gk = new Gk_infoSub();
        try {

            if (doc != null) {
                gk.setIndexno(StringUtil.null2String(doc.get("indexno")));
                gk.setPdate(StringUtil.null2String(doc.get("pdate")));
                String title = StringUtil.null2String(doc.get("title"));
                gk.setTitle(title);
                if (!"".equals(title)) {
                    highlighter.setTextFragmenter(new SimpleFragmenter(title.length()));
                    TokenStream tk = analyzer.tokenStream("title", new StringReader(title));
                    String htext = StringUtil.null2String(highlighter.getBestFragment(tk, title));
                    if (!"".equals(htext)) {
                        gk.setTitle(htext);
                    }
                }
                String keywords = StringUtil.null2String(doc.get("keywords"));
                gk.setKeywords(keywords);
                if (!"".equals(keywords)) {
                    highlighter.setTextFragmenter(new SimpleFragmenter(keywords.length()));
                    TokenStream tk = analyzer.tokenStream("keywords", new StringReader(keywords));
                    String htext = StringUtil.null2String(highlighter.getBestFragment(tk, keywords));
                    if (!"".equals(htext)) {
                        gk.setKeywords(htext);
                    }
                }
                String describes = StringUtil.null2String(doc.get("describes"));
                gk.setDescribes(describes);
                if (!"".equals(describes)) {
                    highlighter.setTextFragmenter(new SimpleFragmenter(describes.length()));
                    TokenStream tk = analyzer.tokenStream("keywords", new StringReader(describes));
                    String htext = StringUtil.null2String(highlighter.getBestFragment(tk, describes));
                    if (!"".equals(htext)) {
                        gk.setDescribes(htext);
                    }
                }

            }
            return gk;
        }
        catch (Exception e) {

            e.printStackTrace();
            return null;
        }
        finally {
            gk = null;
        }

    }

    private synchronized static Object createObj(Document doc) {

        Gk_infoSub gk = new Gk_infoSub();
        try {

            if (doc != null) {
                gk.setIndexno(StringUtil.null2String(doc.get("indexno")));
                gk.setPdate(StringUtil.null2String(doc.get("pdate")));
                gk.setTitle(StringUtil.null2String(doc.get("title")));
                gk.setKeywords(StringUtil.null2String(doc.get("keywords")));
                gk.setDescribes(StringUtil.null2String(doc.get("describes")));
            }
            return gk;
        }
        catch (Exception e) {

            e.printStackTrace();
            return null;
        }
        finally {
            gk = null;
        }

    }
}

 

单字段查询:

        long a = System.currentTimeMillis();
        try {
            int curpage = StringUtil.StringToInt(StringUtil.null2String(form.get("curpage")));
            int pagesize = StringUtil.StringToInt(StringUtil.null2String(form.get("pagesize")));
            String title = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("title")));
            LuceneQuery lu = new LuceneQuery();
            form.addResult("list", lu.queryIndexTitle(title, curpage, pagesize));
            form.addResult("curPage", lu.getCurrentPage());
            form.addResult("pageSize", lu.getPageSize());
            form.addResult("rowCount", lu.getRowCount());
            form.addResult("pageCount", lu.getPages());
        } catch (Exception e) {
            e.printStackTrace();
        }
        long b = System.currentTimeMillis();
        long c = b - a;
        System.out.println("[搜索信息花费时间:" + c + "毫秒]");

多字段查询:

        long a = System.currentTimeMillis();
        try {
            int curpage = StringUtil.StringToInt(StringUtil.null2String(form.get("curpage")));
            int pagesize = StringUtil.StringToInt(StringUtil.null2String(form.get("pagesize")));
            String allkeyword = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("allkeyword")));
            String onekeyword = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("onekeyword")));
            String nokeyword = StringUtil.replaceLuceneStr(StringUtil.null2String(form.get("nokeyword")));
            LuceneQuery lu = new LuceneQuery();
            form.addResult("list", lu.queryIndexFields(allkeyword,onekeyword,nokeyword, curpage, pagesize));
            form.addResult("curPage", lu.getCurrentPage());
            form.addResult("pageSize", lu.getPageSize());
            form.addResult("rowCount", lu.getRowCount());
            form.addResult("pageCount", lu.getPages());
        } catch (Exception e) {
            e.printStackTrace();
        }
        long b = System.currentTimeMillis();
        long c = b - a;
        System.out.println("[高级检索花费时间:" + c + "毫秒]");

4、Lucene通配符查询

            BooleanQuery bQuery = new BooleanQuery();  //组合查询
            if (!"".equals(title)) {
                WildcardQuery w1 = new WildcardQuery(new Term("title", title+ "*"));

                bQuery.add(w1, BooleanClause.Occur.MUST);  //AND
            }
            int hm = start + pageSize;
            TopScoreDocCollector res = TopScoreDocCollector.create(hm, false);
            searcher.search(bQuery, res);

 

5、Lucene嵌套查询

实现SQL:(unitid like ‘unitid%’  and idml like ‘id2%’) or (tounitid like ‘unitid%’ and tomlid like ‘id2%’ and tostate=1)

                    BooleanQuery bQuery = new BooleanQuery();
                    BooleanQuery b1 = new BooleanQuery();
                    WildcardQuery w1 = new WildcardQuery(new Term("unitid", unitid + "*"));
                    WildcardQuery w2 = new WildcardQuery(new Term("idml", id2 + "*"));
                    b1.add(w1, BooleanClause.Occur.MUST);//AND
                    b1.add(w2, BooleanClause.Occur.MUST);//AND
                    bQuery.add(b1, BooleanClause.Occur.SHOULD);//OR
                    BooleanQuery b2 = new BooleanQuery();
                    WildcardQuery w3 = new WildcardQuery(new Term("tounitid", unitid + "*"));
                    WildcardQuery w4 = new WildcardQuery(new Term("tomlid", id2 + "*"));
                    WildcardQuery w5 = new WildcardQuery(new Term("tostate", "1"));
                    b2.add(w3, BooleanClause.Occur.MUST);//AND
                    b2.add(w4, BooleanClause.Occur.MUST);//AND
                    b2.add(w5, BooleanClause.Occur.MUST);//AND
                    bQuery.add(b2, BooleanClause.Occur.SHOULD);//OR

6、Lucene先根据时间排序后分页

下面这种方式不太合理,建议在创建索引库的时候排序,这样查询的时候只用分页即可,若有多个排序条件可单独创建索引库。
int hm = start + pageSize;
Sort sort = new Sort(new SortField(“pdate”, SortField.STRING, true));
TopScoreDocCollector res = TopScoreDocCollector.create(pageSize, false);
searcher.search(bQuery, res);
this.rowCount = res.getTotalHits();
this.pages = (rowCount – 1) / pageSize + 1; //计算总页数
TopDocs tds =searcher.search(bQuery,rowCount,sort);// res.topDocs(start, pageSize);
ScoreDoc[] sd = tds.scoreDocs;
System.out.println(“rowCount:” + rowCount);
int i=0;
for (ScoreDoc scoreDoc : sd) {
i++;
if(i<start){
continue;
}
if(i>hm){
break;
}
Document doc = searcher.doc(scoreDoc.doc);
list.add(createObj(doc));
}


最新的排序写法:

            int hm = start + pageSize;
            Sort sort = new Sort();
            SortField sortField = new SortField("pdate", SortField.STRING, true);
            sort.setSort(sortField);
            TopDocs hits = searcher.search(bQuery, null, hm, sort);
            this.rowCount = hits.totalHits;
            this.pages = (rowCount - 1) / pageSize + 1; //计算总页数
            for (int i = start; i < hits.scoreDocs.length; i++) {
                ScoreDoc sdoc = hits.scoreDocs[i];
                Document doc = searcher.doc(sdoc.doc);
                list.add(createObj(doc));
            }

ps:
周一完成创建索引库定时任务,周二实现模糊查询中文分词高亮显示及分页,今天实现了通配符查询、嵌套查询、先排序后分页,从零接触到实现Lucene主要功能花了三天时间,当然,性能如何还待测试和优化。

20126 月20

Android:扫描获取AP信息

增加权限:

<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />
<uses-permission android:name=”android.permission.CHANGE_WIFI_STATE” />

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
			   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			  showMsg(wifiInfo.toString());//自己的显示方法

			  wifiManager.startScan();
			  List mWifiList = wifiManager.getScanResults();
			  for(int i=0;i<mWifiList.size();i++)
				  logger.d(mWifiList.get(i).toString());//自己重构的日志方法
201112 月22

JAVA源码:将GPS、google地图经纬度坐标转换为百度地图坐标

package smsService;

import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.json.me.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import smsService.cfg.Globals;
import smsService.sms.StringUtil;
import smsService.util.JWD;
import smsService.util.SecBase64;

/**
Wizzer.cn
 */
public class baidu {
    public static void main(String args[]) {
        baidu b = new baidu();
        b.getData("117.3094928", "31.875676");
        System.out.println("");
    }

    public static JWD getData(String jd, String wd) {
        JSONObject holder = new JSONObject();
        String wizzer = "";
        JWD jwd=null;
        try {
            BasicHttpParams httpParameters = new BasicHttpParams();
            // Set the default socket timeout (SO_TIMEOUT)
            HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
            // in milliseconds which is the timeout for waiting for data.
            HttpConnectionParams.setSoTimeout(httpParameters, 15000);

            DefaultHttpClient client = new DefaultHttpClient(httpParameters);
            HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.NETSCAPE);//CookiePolicy.BROWSER_COMPATIBILITY);
            String type="0";//详见百度坐标转换API文档示例
            type=StringUtil.null2String(Globals.SYS_COM_CONFIG.get("sys.baidu.type"));
            HttpGet get = new HttpGet("http://api.map.baidu.com/ag/coord/convert?from="+type +"&to=4&x=" + jd + "&y=" + wd + "&callback=wizzer");
            HttpResponse resp = client.execute(get);
            HttpEntity entity = resp.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity
                    .getContent(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String result = br.readLine();
            while (result != null) {
                sb.append(result);
                result = br.readLine();
            }

            String res = StringUtil.null2String(sb.toString());
            if (res.indexOf("(") > 0 && res.indexOf(")") > 0) {
                String str = res.substring(res.indexOf("(") + 1, res.indexOf(")"));
                String err = res.substring(res.indexOf("error") + 7, res.indexOf("error") + 8);

                if ("0".equals(err)) {
                    jwd=new JWD();
                    JSONObject js = new JSONObject(str);
                    String x = new String(SecBase64.decode(js.getString("x").getBytes()));
                    String y = new String(SecBase64.decode(js.getString("y").getBytes()));
                    jwd.setX(x);
                    jwd.setY(y);
                }
            }
            return jwd;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
201112 月22

JAVA源码:通过google地图API将经纬度坐标转换为位置描述

package smsService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/*
Wizzer.cn
 */
public class Demo {
	public static void main(String[] args) {
		String addr = GetAddr("31.875676", "117.3094928");
		System.out.println(addr);
		//getCoordinate("中国");
	}

	/**
	 * 根据经纬度反向解析地址,有时需要多尝试几次
	 * 注意:(摘自:http://code.google.com/intl/zh-CN/apis/maps/faq.html
	 * 提交的地址解析请求次数是否有限制?) 如果在 24 小时时段内收到来自一个 IP 地址超过 15,000 个地址解析请求, 或从一个 IP
	 * 地址提交的地址解析请求速率过快,Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多,则从该 IP
	 * 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。
	 *
	 * @param latitude
	 *            纬度
	 * @param longitude
	 *            经度
	 * @return
	 */
	public static String GetAddr(String latitude, String longitude) {
		String addr = "";

		// 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不过解析出来的是英文地址
		// 密钥可以随便写一个key=abc
		// output=csv,也可以是xml或json,不过使用csv返回的数据最简洁方便解析
		String url = String.format(
				"http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
				latitude, longitude);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					System.out.println(data);
					String[] retList = data.split(",");
					if (retList.length > 2 && ("200".equals(retList[0]))) {
						addr = retList[2];
						addr = addr.replace("\"", "");
					} else {
						addr = "";
					}
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return addr;
	}

	public static void getCoordinate(String addr)
	{
		String addrs = "";
	    String address = null;
		try {
			address = java.net.URLEncoder.encode(addr,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		};
        String output = "csv";
        String key = "abc";
        String url = String.format("http://maps.google.com/maps/geo?q=%s&output=%s&key=%s", address, output, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        //进行转码
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					System.out.println(data);
					String[] retList = data.split(",");
					/*
		            String latitude = retList[2];
		            String longitude = retList[3];

		            System.out.println("纬度"+ latitude);
		            System.out.println("经度"+ longitude);
		            */

					if (retList.length > 2 && ("200".equals(retList[0]))) {
						addrs = retList[2];
						addrs = addr.replace("\"", "");
					} else {
						addrs = "";
					}
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(addrs);
	}
}
20119 月6

VB实现自动上传文件网页ActiveX控件(模拟form提交)

网页中实现自动上传本地文件,而不需要用户选择,这种应用场景很多,例如业务系统中需要使用的二代身份证扫描器、一体机(扫描仪)、摄像头拍照等。

首先介绍一个国外网站:http://www.planet-source-code.com/ 里面有许多可用的源代码供参考,搜索 upload file 找到 vb6 file uploader (类似的代码比较多,这个是比较好的一个)。

VB通过模拟HTTP POST过程把文件提交至服务器。

Dim WinHttpReq As WinHttp.WinHttpRequest
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Const HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1
Const BOUNDARY = "Xu02=$"
Const HEADER = "--Xu02=$"
Const FOOTER = "--Xu02=$--"

Function UploadFiles(DirPath As String, strFileName As Variant, strFileForm As Variant, strURL As String, _
Optional postName As Variant, Optional postVar As Variant, Optional strUserName As String, _
Optional strPassword As String) As String

    Dim fName As String
    Dim strFile As String
    Dim strBody As String
    Dim aPostBody() As Byte
    Dim nFile As Integer
    Dim p As Integer

    Set WinHttpReq = New WinHttpRequest

    ' Turn error trapping on
    On Error GoTo SaveErrHandler

    ' Assemble an HTTP request.
    WinHttpReq.Open "POST", strURL, False

    If strUserName <> "" And strPassword <> "" Then
        ' Set the user name and password, for server request authentication
        WinHttpReq.SetCredentials strUserName, strPassword, _
        HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
    End If

    '-------------------------- Becareful not to mingle too much here -----------------------------------

    ' Set the header
    WinHttpReq.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & BOUNDARY

    ' Assemble the body
    ' Starting tag
    strBody = HEADER

    For i = 0 To UBound(strFileName)

        ' Grap the name
        fName = strFileName(i)

        ' Grap the file
        strFile = GetFile(DirPath & "\" & fName)

            strBody = strBody & vbCrLf & "Content-Disposition: form-data; name=""" & strFileForm(i) & _
             """; filename=""" & fName & """ " & vbCrLf & "Content-type: file" & _
            vbCrLf & vbCrLf & strFile & vbCrLf

        If i < UBound(strFileName) Then
            ' This is boundary tag between two files
            strBody = strBody & "--Xu02=$"
        End If
        strFile = ""

    Next i

'Posted Variable

    For p = 0 To UBound(postName)
    strBody = strBody & HEADER & vbCrLf
    strBody = strBody & "Content-Disposition: form-data; name=""" & postName(p) & """" & vbCrLf & vbCrLf
    strBody = strBody & postVar(p) & vbCrLf
    'Debug.Print "-----------------------------------------------------------------------------------------------------"
    'Debug.Print "Content-Disposition: form-data; name=""" & postName(p) & """" & vbCrLf & vbCrLf & postVar(p) & vbCrLf
    'Debug.Print "-----------------------------------------------------------------------------------------------------"
    Next p

    ' Ending tag
    strBody = strBody & FOOTER

    ' Because of binary zeros, post body has to convert to byte array
    aPostBody = StrConv(strBody, vbFromUnicode)

    ' Send the HTTP Request.
    WinHttpReq.Send aPostBody

    ' Display the status code and response headers.
    'debug.print WinHttpReq.GetAllResponseHeaders & "  " & WinHttpReq.ResponseText

    UploadFiles = WinHttpReq.ResponseText
    Debug.Print "[UploadScript::UploadFiles]" & vbCrLf & WinHttpReq.ResponseText

    Set WinHttpReq = Nothing
    Exit Function

SaveErrHandler:

    Debug.Print "[UploadScript::UploadFiles]" & vbCrLf & Err.Description
    UploadFiles = WinHttpReq.ResponseText
    Set WinHttpReq = Nothing

End Function

Function GetFile(strFileName As String) As String

    Dim strFile As String

    ' Grap the file
    nFile = FreeFile
    Open strFileName For Binary As #nFile
    strFile = String(LOF(nFile), " ")
    Get #nFile, , strFile
    Close #nFile

    GetFile = strFile

End Function

'-----------------------------------------------------------
Private Sub Command1_Click()
Dim pst As New clsUploadEngine

'file path (make sure put "\" after folder name)
filepath = App.Path & "\sample\"

'filename array
filearr = Array("scenery1.jpg", "scenery2.jpg", "scenery3.jpg")

'form file post name (equivalent to <input type="file" name="filename">
fileform = Array("fileA", "fileB", "fileC")

'url to post file/information
uploadurl = "http://127.0.0.1:8080/savefile.jsp"

'post parameter & posted variable (optional)
'if no post parameter, just put dummy post, if not error will occur
postparam = Array("id", "uname", "passwd", "op")
postVar = Array("1", "root", "", "tdrupload")

pst.UploadFiles CStr(filepath), filearr, fileform, CStr(uploadurl), postparam, postVar

End Sub

在此基础上,做成ActiveX控件即可。但问题是这个源码上传到服务器的文本文件虽然看起来正常但文件结尾会有空编码、图片损坏。囧。

后来发现 WebNoteEditor 可以实现粘贴QQ截图,自动把文件上传到服务器,于是联系作者。作者是个好人哈,分享了一些经验甚至代码。目前在作者的帮助下,已实现的网页控件的文件自动上传功能,可传多个文件、多表单项。

下面要解决如何在线安装的问题了……

20118 月31

百度地图API:GPS经纬度转换整合版

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
	<script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2"></script>
	<script type="text/javascript" src="http://dev.baidu.com/wiki/static/map/API/examples/script/convertor.js"></script>
</head>
<body style="padding:4px 0px 4px 4px;overflow-y:scroll">
<div style="position:relative; width:100%;height:405px;border:1px solid #D4D0C8;" id="container"></div>
<script language="javascript" id="mapscript">
document.getElementById("container").style.height = document.body.clientHeight+18;
var map = new BMap.Map("container");
map.centerAndZoom("兰州", 5);
map.addControl(new BMap.NavigationControl());
map.enableScrollWheelZoom();//启动鼠标滚轮缩放地图

map.addEventListener('load',function(){

//增加一个标注点
//doaddpoint('<%=appname%>/img/private/images/icon_home1.png', '', '<%=locdata.getRegion()%><%=locdata.getCity()%><%=locdata.getStreet()%>', '', '<%=jd%>', '<%=wd%>', '<%=locdata.getPhone()%>', '<%=Sys_userCtl.getUserNameByloginNames(locdata.getLoginname())%>','<%=locdata.getCtime()%>','#ff0000','<%=Loc_dataCtl.getLocType(locdata)%>');

});
//新增一个点时处理方法
function doaddpoint(img, name, dz, id, jd, wd, dh, lxr,sm,color,type)
{
var sContent ="<div class='tab_TextInput_map' style='width:250px;'><table id='TextInput_map' align=left><tr><td><b>人员姓名:</b></td><td>" + lxr + "</td></tr><tr><td><b>手机号码:</b></td><td>" + dh + "</td></tr><tr><td><b>定位时间:</b></td><td>" + sm + "</td></tr><tr><tr><td><b>上传地址:</b></td><td>" + dz + "</td></tr><tr><td><b>定位方式:</b></td><td>" + type + "</td></tr></table></div>";
var gpsPoint = new BMap.Point(jd,wd);

translateOptions = function (point){
var marker = new BMap.Marker(point);

var infoWindow = new BMap.InfoWindow(sContent);  // 创建信息窗口对象
map.addOverlay(marker);
marker.addEventListener("click", function(){
   this.openInfoWindow(infoWindow);
});
marker.setLabel(new BMap.Label("<span style='color:blue;font-size:16px;font-weight:bold;'>" + lxr +"</span>",{offset:new BMap.Size(20,0)}));   

}
BMap.Convertor.translate(gpsPoint,0,translateOptions);

}

</script>
</div>
</form>
</body>
</html>
20117 月31

Android开发:休眠唤醒或开机后cmwap/cmnet网络不能连接的解决办法

Android手机(移动GSM)在休眠或开机后不能成功启用网络链接(设置都正常),有时候甚至状态栏图标是连接的,但网络依旧不可用。

如下解决方法,不知可通用,但测试HTC野火手机移动版可使用:

(被这个问题折腾死了,从本站相关文章可以看到,之前尝试了APN切换也不行,估计是网络enable==false)

package com.wiz.tools;

import java.lang.reflect.Method;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
 * Wizzer.cn
 * @author Wizzer
 *
 */
public class NetCheck {
	public static final Uri APN_URI = Uri.parse("content://telephony/carriers");
	public static final Uri DEFAULTAPN_URI = Uri
			.parse("content://telephony/carriers/restore");
	public static final Uri CURRENT_APN_URI = Uri
			.parse("content://telephony/carriers/preferapn");
	public static Context c1;

	public static String getCurrentAPNFromSetting(ContentResolver resolver) {
		Cursor cursor = null;
		try {
			cursor = resolver.query(CURRENT_APN_URI, null, null, null, null);
			String curApnId = null;
			String apnName1 = null;
			if (cursor != null && cursor.moveToFirst()) {
				curApnId = cursor.getString(cursor.getColumnIndex("_id"));
				apnName1 = cursor.getString(cursor.getColumnIndex("apn"));
			}
			Log.e("NetCheck getCurrentAPNFromSetting", "curApnId:" + curApnId
					+ " apnName1:" + apnName1);
			// find apn name from apn list
			if (curApnId != null) {
				cursor = resolver.query(APN_URI, null, " _id = ?",
						new String[] { curApnId }, null);
				if (cursor != null && cursor.moveToFirst()) {
					String apnName = cursor.getString(cursor
							.getColumnIndex("apn"));
					return apnName;
				}
			}

		} catch (SQLException e) {
			Log.e("NetCheck getCurrentAPNFromSetting", e.getMessage());
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return null;
	}

	public static int updateCurrentAPN(ContentResolver resolver, String newAPN) {
		Cursor cursor = null;
		try {
			// get new apn id from list
			cursor = resolver.query(APN_URI, null, " apn = ? and current = 1",
					new String[] { newAPN.toLowerCase() }, null);
			String apnId = null;
			if (cursor != null && cursor.moveToFirst()) {
				apnId = cursor.getString(cursor.getColumnIndex("_id"));
			}
			Log.e("NetCheck updateCurrentAPN", "apnId:" + apnId);
			// set new apn id as chosen one
			if (apnId != null) {
				ContentValues values = new ContentValues();
				values.put("apn_id", apnId);
				resolver.update(CURRENT_APN_URI, values, null, null);
			} else {
				// apn id not found, return 0.
				return 0;
			}
		} catch (SQLException e) {
			Log.e("NetCheck updateCurrentAPN", e.getMessage());
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		// update success
		return 1;
	}

	public String getApn(Context c) {
		boolean netSataus = false;

		ConnectivityManager conManager = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);	
		if (conManager.getActiveNetworkInfo() != null) {
			netSataus = conManager.getActiveNetworkInfo().isAvailable();

		}
		NetworkInfo info = conManager
		.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		String oldAPN = StringUtils.null2String(info.getExtraInfo());
		Log
		.e("NetCheck getApn", "oldAPN:" + oldAPN + " netSataus:"
				+ netSataus);
		if (netSataus == false) {
			Log.e("NetCheck getApn", "setMobileDataEnabled(true)");
			setMobileDataEnabled(c, true);	

			try {
				Thread.sleep(4012);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if("".equals(oldAPN)){			
			updateCurrentAPN(c.getContentResolver(), "cmnet");
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		info = conManager
		.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		oldAPN = StringUtils.null2String(info.getExtraInfo());
		Log
				.e("NetCheck getApn", "newApn:" + oldAPN);
		return oldAPN.toLowerCase();
	}

	public boolean setMobileDataEnabled(Context c, boolean enabled) {
		final TelephonyManager mTelManager;
		mTelManager = (TelephonyManager) c
				.getSystemService(Context.TELEPHONY_SERVICE);
		try {

			Method m = mTelManager.getClass()
					.getDeclaredMethod("getITelephony");
			m.setAccessible(true);
			Object telephony = m.invoke(mTelManager);
			m = telephony.getClass().getMethod(
					(enabled ? "enable" : "disable") + "DataConnectivity");
			m.invoke(telephony);
			return true;
		} catch (Exception e) {
			Log.e("NetCheck ", "cannot fake telephony", e);
			return false;
		}
	}

}
20117 月15

Android 开发:APN网络切换之CMNET

最近被Android系统的APN自动切换网络问题折腾死了,软件使用CMNET网络,而系统自带的一些软件必须使用CMWAP,或者手机厂家搞的一些后台服务或者流氓软件总是在切换网络。没办法,只好想个解决之道了。

我的解决方案是:
1、在程序启动时,注册 Receiver 监视网络状态,当网络发生变化判断不是CMNET时则切换网络;
2、为了保险起见,在每个HTTP链接请求前加上网络判断。

本软件主要实现了功能如下:
拍照、定位、表单文件上传、查询、短信拦截(用于通过短信指令获得手机当前位置)、拨打电话、定时自动上传定位数据、版本更新等。

如下粘贴APN网络判断网站代码:
1、NetworkChangeReceiver  网络状态监视

package com.wiz.receiver;

import com.wiz.tools.NetCheck;
import com.wiz.tools.StringUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class NetworkChangeReceiver  extends BroadcastReceiver {
	NetCheck netCheck=new NetCheck();
	 public void onReceive(Context context, Intent intent) {
		 Log.e("NetworkChangeReceiver", "onReceive");
		 ConnectivityManager conManager= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 

        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            NetworkInfo info = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            String apn = StringUtils.null2String(info.getExtraInfo());
            if (!"cmnet".equals(apn.toLowerCase())) {
            	netCheck.checkNetworkInfo(context);
            }
        }
    }
}

2、Activity 中注册 NetworkChangeReceiver

NetworkChangeReceiver ncr = new NetworkChangeReceiver();
IntentFilter upIntentFilter = new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(ncr, upIntentFilter);// 网络状态监控

3、APN判断及网络切换

package com.wiz.tools;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;

public class NetCheck {
	public static final Uri APN_URI = Uri.parse("content://telephony/carriers");
	public static final Uri CURRENT_APN_URI = Uri
			.parse("content://telephony/carriers/preferapn");
	public static String getCurrentAPNFromSetting(ContentResolver resolver) {
        Cursor cursor = null;
        try {
            cursor = resolver.query(CURRENT_APN_URI, null, null, null, null);
            String curApnId = null;
            String apnName1=null;
            if (cursor != null && cursor.moveToFirst()) {
                curApnId = cursor.getString(cursor.getColumnIndex("_id"));
                apnName1 = cursor.getString(cursor.getColumnIndex("apn"));
            }
            cursor.close();
            Log.e("NetCheck getCurrentAPNFromSetting","curApnId:"+curApnId+" apnName1:"+apnName1);
            //find apn name from apn list
            if (curApnId != null) {
                cursor = resolver.query(APN_URI, null, " _id = ?", new String[]{curApnId}, null);
                if (cursor != null && cursor.moveToFirst()) {
                    String apnName = cursor.getString(cursor.getColumnIndex("apn"));
                    return apnName;
                }
            } 

        } catch (SQLException e) {
            Log.e("NetCheck getCurrentAPNFromSetting",e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        } 

        return null;
}
	public static int updateCurrentAPN(ContentResolver resolver, String newAPN) {
        Cursor cursor = null;
        try {
            //get new apn id from list
            cursor = resolver.query(APN_URI, null, " apn = ? and current = 1", new String[]{newAPN.toLowerCase()}, null);
            String apnId = null;
            if (cursor != null && cursor.moveToFirst()) {
                apnId = cursor.getString(cursor.getColumnIndex("_id"));
            }
            cursor.close();
            Log.e("NetCheck updateCurrentAPN","apnId:"+apnId);
            //set new apn id as chosen one
            if (apnId != null) {
                ContentValues values = new ContentValues();
                values.put("apn_id", apnId);
                resolver.update(CURRENT_APN_URI, values, null, null);
            } else {
                //apn id not found, return 0.
                return 0;
            }
        } catch (SQLException e) {
        	Log.e("NetCheck updateCurrentAPN",e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        } 

        //update success
        return 1;
} 

	public boolean checkNetworkInfo(Context c) {
		boolean ret=false;
		ConnectivityManager conManager= (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		boolean internet=conManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
        String oldAPN = StringUtils.null2String(info.getExtraInfo());
        String oldSQLAPN=StringUtils.null2String(getCurrentAPNFromSetting(c.getContentResolver()));

        Log.e("NetCheck checkNetworkInfo","oldAPN:"+oldAPN+" oldSQLAPN:"+oldSQLAPN);
        if (internet==false||!"cmnet".equals(oldAPN.toLowerCase())||!"cmnet".equals(oldSQLAPN.toLowerCase())) {
            if("cmwap".equals(oldAPN.toLowerCase())&&"cmnet".equals(oldSQLAPN.toLowerCase())){
            	updateCurrentAPN(c.getContentResolver(), "cmwap");
            	try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
            }
            updateCurrentAPN(c.getContentResolver(), "cmnet");
            try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            ret=true;
        }
        return ret; 

	}
}

4、HTTP请求前的判断

if (nc.checkNetworkInfo(LoginActivity.this)) {
				Thread.sleep(5000);// 设置cmnet网络
			}

本文原创,转载请注明来源 wizzer.cn。

20115 月28

Android:指定分辨率和清晰度的图片压缩方法源码

public void transImage(String fromFile, String toFile, int width, int height, int quality)
	{
		try
		{
			Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
			int bitmapWidth = bitmap.getWidth();
			int bitmapHeight = bitmap.getHeight();
			// 缩放图片的尺寸
			float scaleWidth = (float) width / bitmapWidth;
			float scaleHeight = (float) height / bitmapHeight; 
			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleHeight);
			// 产生缩放后的Bitmap对象
			Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
			// save file
			File myCaptureFile = new File(toFile);
			FileOutputStream out = new FileOutputStream(myCaptureFile);
			if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){
				out.flush();
				out.close();
			}
			if(!bitmap.isRecycled()){
				bitmap.recycle();//记得释放资源,否则会内存溢出
			}
			if(!resizeBitmap.isRecycled()){
				resizeBitmap.recycle();
			}

		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
	}
20115 月19

Android:解决ProgressDialog提示框不转动

ProgressDialog 解决“第一次执行图标转动,第二次执行不转动”代码:

@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			progressDialog = new ProgressDialog(LoginActivity.this);
			progressDialog.setMessage("正在登陆,请稍等...");
			progressDialog.setCancelable(true);
			// 设置ProgressDialog 是否可以按退回按键取消
			return progressDialog;
		default:
			return null;
		}
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case PROGRESS_DIALOG:
			dialog
					.setOnDismissListener(new DialogInterface.OnDismissListener() {
						@Override
						public void onDismiss(DialogInterface dialog) {
							removeDialog(PROGRESS_DIALOG);//这个起作用
							if (progressThread != null) {
								progressThread = null;
							}
						}
					});
		}
	}
20115 月19

Android:设置APN为cmnet源码

public class APNActivity extends Activity {

        public static final Uri APN_URI = Uri.parse("content://telephony/carriers");
        public static final Uri CURRENT_APN_URI = Uri.parse("content://telephony/carriers/preferapn");

        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                int _cmnetId = addAPN();
                SetAPN(_cmnetId);
        }
       public void checkAPN(){
      // 检查当前连接的APN
              Cursor cr = getContentResolver().query(CURRENT_APN_URI, null, null,
              null, null);
              while (cr != null && cr.moveToNext()) {
                  // APN id
                  String id = cr.getString(cr.getColumnIndex("_id"));
                  // APN name
                  String apn = StringUtils.null2String(cr
                  .getString(cr.getColumnIndex("apn")));
                  // Toast.makeText(getApplicationContext(),
                  // "当前 id:" + id + " apn:" + apn, Toast.LENGTH_LONG).show();

       }

        //新增一个cmnet接入点
        public int addAPN() {
                int id = -1;
                ContentResolver resolver = this.getContentResolver();
                ContentValues values = new ContentValues();
                values.put("name", "cmnet");
                values.put("apn", "cmnet");
                Cursor c = null;
                Uri newRow = resolver.insert(APN_URI, values);
                if (newRow != null) {
                        c = resolver.query(newRow, null, null, null, null);
                        int idIndex = c.getColumnIndex("_id");
                        c.moveToFirst();
                        id = c.getShort(idIndex);
                }
                if (c != null)
                        c.close();
                return id;
        }
        //设置接入点
        public void SetAPN(int id) {
                ContentResolver resolver = this.getContentResolver();
                ContentValues values = new ContentValues();
                values.put("apn_id", id);
                resolver.update(CURRENT_APN_URI, values, null, null);
        }
}
20115 月4

Android 手机端与服务端POST数据交互类

 

package com.wizzer.tools;

import java.io.*;
import java.net.URLEncoder;

import java.util.*;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;

public class BaseProtocol 
{
	private StringBuilder sb = new StringBuilder();
	private HttpClient httpClient;
	private HttpPost httpRequest;
	private HttpResponse response;
	private List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
	private static final int DIALOG1_KEY = 0;
	private static final int DIALOG2_KEY = 1;

	public BaseProtocol()
	{
		httpClient = new DefaultHttpClient();
	}

	/**
	 * *向服务器端发送请求 * *@paramurl *@throwsException
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public void pack(String url) throws Exception
	{
		httpClient = new DefaultHttpClient();
		httpRequest = new HttpPost(url);
		httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
		response = httpClient.execute(httpRequest);
	}

	/** *得到返回数据 * *@paramurl *@return *@throwsException */

	public String parse() throws Exception
	{
		// TODO状态处理500200
		if (response.getStatusLine().getStatusCode() == 200)
		{
			BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			for (String s = bufferedReader2.readLine(); s != null; s = bufferedReader2.readLine())
			{
				sb.append(s);
			}
		}
		return sb.toString();
	}

	/***
	 * 向服务器发送信息 * *@paramkey *@paramvalue
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public void addNameValuePair(String key, String value) throws UnsupportedEncodingException
	{
		nameValuePair.add(new BasicNameValuePair(key, URLEncoder.encode(value, HTTP.UTF_8)));
	}

	/** *返回JSONArray对象数据模型 * *@return *@throwsJSONException */

	public JSONArray getJSON() throws JSONException
	{
		return new JSONArray(sb.toString());
	}

}
201012 月31

JAVA发送EMAIL的例子

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: Wizzer
 * Date: 2010-12-29
 * Time: 16:39:50
 * To change this template use File | Settings | File Templates.
 */
public class Mail {
    public static void main(String args[]) throws MessagingException, UnsupportedEncodingException {
    Properties props = new Properties();
    props.put("mail.smtp.host","smtp.qq.com");
    props.put("mail.smtp.auth","true");
    PopupAuthenticator auth = new PopupAuthenticator(); 
    Session session = Session.getInstance(props, auth);
    MimeMessage message = new MimeMessage(session);
    Address addressFrom = new InternetAddress(PopupAuthenticator.mailuser+"@qq.com", "George Bush");
    Address addressTo = new InternetAddress("116****@qq.com", "George Bush");//收件人
    message.setText("邮件发送成功");
    message.setSubject("Javamal最终测试");
    message.setFrom(addressFrom);
    message.addRecipient(Message.RecipientType.TO,addressTo);
    message.saveChanges();
    Transport transport = session.getTransport("smtp");
    transport.connect("smtp.qq.com", PopupAuthenticator.mailuser,PopupAuthenticator.password);
    transport.send(message);
    transport.close();
    }

}
class PopupAuthenticator extends Authenticator {
public static final String mailuser="wizzer"; 
public static final String password="********";
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailuser,password);
}
}
201011 月17

新浪微博Android 客户端通过HTTP POST发布图片和文字源代码(作废)

1、发送图片+文字

要特别注意,图片的文件名要为 pic 才会被新浪接收。

              Map map = new HashMap();
	   map.put("source", "appkey");//改成自己的key
	   map.put("status", txt);
	   postImg("http://api.t.sina.com.cn/statuses/upload.json",map,Environment.getExternalStorageDirectory()+ "/temp.jpg"
								,"帐号名字","密码");
              /**
	 * 直接通过HTTP协议提交数据到服务器,实现表单提交功能
	 * @param actionUrl 上传路径
	 * @param params 请求参数 key为参数名,value为参数值
	 * @param filename 上传文件
	 * @param username 用户名
	 * @param password 密码
	 */
	private void postImg(String actionUrl,Map<String, String> params, String  filename,String username,String password) {
		try {
			String BOUNDARY = "--------------et567z"; //数据分隔线
			String MULTIPART_FORM_DATA = "Multipart/form-data";  

			URL url = new URL(actionUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

			conn.setDoInput(true);//允许输入
			conn.setDoOutput(true);//允许输出
			conn.setUseCaches(false);//不使用Cache
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
			String usernamePassword=username+":"+password;
			conn.setRequestProperty("Authorization","Basic "+new String(SecBase64.encode(usernamePassword.getBytes())));

			StringBuilder sb = new StringBuilder();  

			//上传的表单参数部分,格式请参考文章
			for (Map.Entry<String, String> entry : params.entrySet()) {//构建表单字段内容
				sb.append("--");
				sb.append(BOUNDARY);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
				sb.append(entry.getValue());
				sb.append("\r\n");
			}
			//            System.out.println(sb.toString());
			DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
			outStream.write(sb.toString().getBytes());//发送表单字段数据
			byte[] content = readFileImage(filename);
			//上传的文件部分,格式请参考文章
			//System.out.println("content:"+content.toString());
			StringBuilder split = new StringBuilder();
			split.append("--");
			split.append(BOUNDARY);
			split.append("\r\n");
			split.append("Content-Disposition: form-data;name=\"pic\";filename=\"temp.jpg\"\r\n");
			split.append("Content-Type: image/jpg\r\n\r\n");
			System.out.println(split.toString());
			outStream.write(split.toString().getBytes());
			outStream.write(content, 0, content.length);
			outStream.write("\r\n".getBytes());  

			byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//数据结束标志
			outStream.write(end_data);
			outStream.flush();
			int cah = conn.getResponseCode();
			//            if (cah != 200) throw new RuntimeException("请求url失败:"+cah);
			if(cah == 200)//如果发布成功则提示成功
			{
				/*读返回数据*/
				//String strResult = EntityUtils.toString(httpResponse.getEntity()); 

				new AlertDialog.Builder(Main.this)
				// Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
				.setTitle("")// 设置对话框的标题
				.setPositiveButton("确定",// 设置对话框的确认按钮
						new DialogInterface.OnClickListener() {// 设置确认按钮的事件
					public void onClick(DialogInterface dialog, int which) {

					}})
					.setMessage(" 发布成功 ")// 设置对话框的内容
					.show();
			}
			else if(cah == 400)
			{
				new AlertDialog.Builder(Main.this)
				// Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
				.setTitle("")// 设置对话框的标题
				.setPositiveButton("确定",// 设置对话框的确认按钮
						new DialogInterface.OnClickListener() {// 设置确认按钮的事件
					public void onClick(DialogInterface dialog, int which) {

					}})
					.setMessage(" 发布失败  \n 不可连续发布相同内容 ")// 设置对话框的内容
					.show();
			}else{
				throw new RuntimeException("请求url失败:"+cah);
			} 

			//            InputStream is = conn.getInputStream();
			//            int ch;
			//            StringBuilder b = new StringBuilder();
			//            while( (ch = is.read()) != -1 ){
			//                b.append((char)ch);
			//            }
			outStream.close();
			conn.disconnect();
		}
		catch (IOException e)
		{
			e.printStackTrace(); 

		}
		catch (Exception e)
		{
			e.printStackTrace();  

		}  

	}

             public static byte[] readFileImage(String filename) throws IOException {
		BufferedInputStream bufferedInputStream = new BufferedInputStream(
				new FileInputStream(filename));
		int len = bufferedInputStream.available();
		byte[] bytes = new byte[len];
		int r = bufferedInputStream.read(bytes);
		if (len != r) {
			bytes = null;
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}

2、只发文字

  //POST发布文本信息
	    public  void sendMsg(String status,String username,String password){
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost("http://api.t.sina.com.cn/statuses/update.json");
		        //NameValuePair实现请求参数的封装

		        List  params = new ArrayList ();
		        params.add(new BasicNameValuePair("source", "4016954419"));
		        params.add(new BasicNameValuePair("status", status));
		        try
		        { 

		          //添加请求参数到请求对象

		        	httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		        	httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); 

		        	String data=username+":"+password;
		        	httppost.addHeader("Authorization","Basic "+new String(SecBase64.encode(data.getBytes())));
		        	httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");

		          //发送请求并等待响应
		          HttpResponse httpResponse = new DefaultHttpClient().execute(httppost);
		          //若状态码为200 ok
		          if(httpResponse.getStatusLine().getStatusCode() == 200)
		          {
		            //读返回数据
		            //String strResult = EntityUtils.toString(httpResponse.getEntity()); 

		            new AlertDialog.Builder(Main.this)
					// Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
					.setTitle("")// 设置对话框的标题
					.setPositiveButton("确定",// 设置对话框的确认按钮
				    new DialogInterface.OnClickListener() {// 设置确认按钮的事件
				        public void onClick(DialogInterface dialog, int which) {

				    }})
					.setMessage(" 发布成功 ")// 设置对话框的内容
					.show();
		          }
		          else if(httpResponse.getStatusLine().getStatusCode() == 400)
		          {
		        	  new AlertDialog.Builder(Main.this)
						// Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
						.setTitle("")// 设置对话框的标题
						.setPositiveButton("确定",// 设置对话框的确认按钮
				    new DialogInterface.OnClickListener() {// 设置确认按钮的事件
				        public void onClick(DialogInterface dialog, int which) {

				    }})
						.setMessage(" 发布失败  \n 不可连续发布相同内容 ")// 设置对话框的内容
						.show();
		          } 

		        }
		        catch (ClientProtocolException e)
		        {
		          e.printStackTrace();
		          et.setText(et.getText()+" Error1:"+e.getMessage());
		        }
		        catch (IOException e)
		        {
		          e.printStackTrace();
		          et.setText(et.getText()+" Error2:"+e.getMessage());
		        }
		        catch (Exception e)
		        {
		          e.printStackTrace();
		          et.setText(et.getText()+" Error3:"+e.getMessage());
		        }  

		 }

3、加密类 SecBase64.java

package wizzer.cn.app;

public class SecBase64 {
private static final byte[] encodingTable = { (byte) 'A', (byte) 'B',
    (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
    (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
    (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q',
    (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V',
    (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a',
    (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
    (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k',
    (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
    (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
    (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
    (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
    (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
    (byte) '+', (byte) '/' };
private static final byte[] decodingTable;
static {
   decodingTable = new byte[128];
   for (int i = 0; i < 128; i++) {
    decodingTable[i] = (byte) -1;
   }
   for (int i = 'A'; i <= 'Z'; i++) {
    decodingTable[i] = (byte) (i - 'A');
   }
   for (int i = 'a'; i <= 'z'; i++) {
    decodingTable[i] = (byte) (i - 'a' + 26);
   }
   for (int i = '0'; i <= '9'; i++) {
    decodingTable[i] = (byte) (i - '0' + 52);
   }
   decodingTable['+'] = 62;
   decodingTable['/'] = 63;
}

//加密

public static byte[] encode(byte[] data) {
   byte[] bytes;
   int modulus = data.length % 3;
   if (modulus == 0) {
    bytes = new byte[(4 * data.length) / 3];
   } else {
    bytes = new byte[4 * ((data.length / 3) + 1)];
   }
   int dataLength = (data.length - modulus);
   int a1;
   int a2;
   int a3;
   for (int i = 0, j = 0; i < dataLength; i += 3, j += 4) {
    a1 = data[i] & 0xff;
    a2 = data[i + 1] & 0xff;
    a3 = data[i + 2] & 0xff;
    bytes[j] = encodingTable[(a1 >>> 2) & 0x3f];
    bytes[j + 1] = encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f];
    bytes[j + 2] = encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f];
    bytes[j + 3] = encodingTable[a3 & 0x3f];
   }
   int b1;
   int b2;
   int b3;
   int d1;
   int d2;
   switch (modulus) {
   case 0: 
    break;
   case 1:
    d1 = data[data.length - 1] & 0xff;
    b1 = (d1 >>> 2) & 0x3f;
    b2 = (d1 << 4) & 0x3f;
    bytes[bytes.length - 4] = encodingTable[b1];
    bytes[bytes.length - 3] = encodingTable[b2];
    bytes[bytes.length - 2] = (byte) '=';
    bytes[bytes.length - 1] = (byte) '=';
    break;
   case 2:
    d1 = data[data.length - 2] & 0xff;
    d2 = data[data.length - 1] & 0xff;
    b1 = (d1 >>> 2) & 0x3f;
    b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
    b3 = (d2 << 2) & 0x3f;
    bytes[bytes.length - 4] = encodingTable[b1];
    bytes[bytes.length - 3] = encodingTable[b2];
    bytes[bytes.length - 2] = encodingTable[b3];
    bytes[bytes.length - 1] = (byte) '=';
    break;
   }
   return bytes;
}

//解密

public static byte[] decode(byte[] data) {
   byte[] bytes;
   byte b1;
   byte b2;
   byte b3;
   byte b4;
   data = discardNonBase64Bytes(data);
   if (data[data.length - 2] == '=') {
    bytes = new byte[(((data.length / 4) - 1) * 3) + 1];
   } else if (data[data.length - 1] == '=') {
    bytes = new byte[(((data.length / 4) - 1) * 3) + 2];
   } else {
    bytes = new byte[((data.length / 4) * 3)];
   }
   for (int i = 0, j = 0; i < (data.length - 4); i += 4, j += 3) {
    b1 = decodingTable[data[i]];
    b2 = decodingTable[data[i + 1]];
    b3 = decodingTable[data[i + 2]];
    b4 = decodingTable[data[i + 3]];
    bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
    bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
    bytes[j + 2] = (byte) ((b3 << 6) | b4);
   }
   if (data[data.length - 2] == '=') {
    b1 = decodingTable[data[data.length - 4]];
    b2 = decodingTable[data[data.length - 3]];
    bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
   } else if (data[data.length - 1] == '=') {
    b1 = decodingTable[data[data.length - 4]];
    b2 = decodingTable[data[data.length - 3]];
    b3 = decodingTable[data[data.length - 2]];
    bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
    bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
   } else {
    b1 = decodingTable[data[data.length - 4]];
    b2 = decodingTable[data[data.length - 3]];
    b3 = decodingTable[data[data.length - 2]];
    b4 = decodingTable[data[data.length - 1]];
    bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
    bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
    bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
   }
   return bytes;
}

//解密

public static byte[] decode(String data) {
   byte[] bytes;
   byte b1;
   byte b2;
   byte b3;
   byte b4;
   data = discardNonBase64Chars(data);
   if (data.charAt(data.length() - 2) == '=') {
    bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];
   } else if (data.charAt(data.length() - 1) == '=') {
    bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];
   } else {
    bytes = new byte[((data.length() / 4) * 3)];
   }
   for (int i = 0, j = 0; i < (data.length() - 4); i += 4, j += 3) {
    b1 = decodingTable[data.charAt(i)];
    b2 = decodingTable[data.charAt(i + 1)];
    b3 = decodingTable[data.charAt(i + 2)];
    b4 = decodingTable[data.charAt(i + 3)];
    bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
    bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
    bytes[j + 2] = (byte) ((b3 << 6) | b4);
   }
   if (data.charAt(data.length() - 2) == '=') {
    b1 = decodingTable[data.charAt(data.length() - 4)];
    b2 = decodingTable[data.charAt(data.length() - 3)];
    bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
   } else if (data.charAt(data.length() - 1) == '=') {
    b1 = decodingTable[data.charAt(data.length() - 4)];
    b2 = decodingTable[data.charAt(data.length() - 3)];
    b3 = decodingTable[data.charAt(data.length() - 2)];
    bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
    bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
   } else {
    b1 = decodingTable[data.charAt(data.length() - 4)];
    b2 = decodingTable[data.charAt(data.length() - 3)];
    b3 = decodingTable[data.charAt(data.length() - 2)];
    b4 = decodingTable[data.charAt(data.length() - 1)];
    bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
    bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
    bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
   }
   return bytes;
}

private static byte[] discardNonBase64Bytes(byte[] data) {
   byte[] temp = new byte[data.length];
   int bytesCopied = 0;
   for (int i = 0; i < data.length; i++) {
    if (isValidBase64Byte(data[i])) {
     temp[bytesCopied++] = data[i];
    }
   }
   byte[] newData = new byte[bytesCopied];
   System.arraycopy(temp, 0, newData, 0, bytesCopied);
   return newData;
}

private static String discardNonBase64Chars(String data) {
   StringBuffer sb = new StringBuffer();
   int length = data.length();
   for (int i = 0; i < length; i++) {
    if (isValidBase64Byte((byte) (data.charAt(i)))) {
     sb.append(data.charAt(i));
    }
   }
   return sb.toString();
}

private static boolean isValidBase64Byte(byte b) {
   if (b == '=') {
    return true;
   } else if ((b < 0) || (b >= 128)) {
    return false;
   } else if (decodingTable[b] == -1) {
    return false;
   }
   return true;
}

//测试类
public static void main(String[] args) {
   String data = "wizzer@qq.com:etpass";
   byte[] result = SecBase64.encode(data.getBytes());// 加密
   System.out.println("Basic "+data);
   System.out.println("Basic "+new String(result));
   System.out.println(new String(SecBase64.decode(new String(result))));// 解密
   }
}
201011 月16

Android 2.1 GPS定位和拍照功能代码

1、GPS功能代码

private void getLocation()
	{
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				 200, 0, locationListener);

	}
	private final LocationListener locationListener = new LocationListener() {
	    public void onLocationChanged(Location location) { //当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
	        // log it when the location changes
	        if (location != null) {
	        	Lat.setText(String.valueOf(location.getLatitude()));
	        	Lon.setText(String.valueOf(location.getLongitude()));

	        }
	    }

	    public void onProviderDisabled(String provider) {
	    // Provider被disable时触发此函数,比如GPS被关闭
	    }

	    public void onProviderEnabled(String provider) {
	    //  Provider被enable时触发此函数,比如GPS被打开
	    }

	    public void onStatusChanged(String provider, int status, Bundle extras) {
	    // Provider的转态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
	    }
	};

2、拍照功能代码

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     // Hide the window title.
		requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);
        imageView = (ImageView) this.findViewById(R.id.iv1);
		Button button = (Button) this.findViewById(R.id.bt1);
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
						.fromFile(new File(Environment
								.getExternalStorageDirectory(), "temp.jpg")));
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
				startActivityForResult(intent, 0);
			}
		});

    }
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
			this.imageView.setImageDrawable(Drawable.createFromPath(new File(
					Environment.getExternalStorageDirectory(), "temp.jpg")
					.getAbsolutePath()));

		}
	}

3、退出程序确认

public boolean onKeyDown(int keyCode, KeyEvent event) {

		//按下键盘上返回按钮
		if(keyCode == KeyEvent.KEYCODE_BACK){
			new AlertDialog.Builder(Main.this)
			// Main.this视情况而定,这个一般是指当前显示的Activity对应的XML视窗。
			.setTitle("")// 设置对话框的标题
			.setMessage(" 确定退出? ")// 设置对话框的内容
			.setPositiveButton("确定",// 设置对话框的确认按钮
			    new DialogInterface.OnClickListener() {// 设置确认按钮的事件
			        public void onClick(DialogInterface dialog, int which) {
			            //退出程序
			            android.os.Process.killProcess(android.os.Process.myPid());
			    }})
			.setNegativeButton("取消",// 设置对话框的取消按钮
			    new DialogInterface.OnClickListener() {// 设置取消按钮的事件
			        public void onClick(DialogInterface dialog, int which) {
			            // 如果你什么操作都不做,可以选择不写入任何代码
			            dialog.cancel();
			    }}
			).show();

			return true;
		}else{		
			return super.onKeyDown(keyCode, event);
		}
	}
20109 月22

WM windows mobile 6.1 C#网络开发,程序自动升级等

终于的终于,还是用C#开发了,仿照了一些M8上软件界面。。

分享一些经验,由于时间太紧,有些功能是比较土的方法暂时实现的,之后还需升级。

1、网络传输

 public static string Login(string userName, string password)
        {
            string LOGIN_RES = "";
            try
            {

                string url = com.LOGIN_URL ;//url
                url = url + "&username=" + userName;
                url = url + "&password=" + password;

                HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
                objRequest.Method = "GET";
                objRequest.Timeout = 60 * 1000;
                //WebProxy proxy = new WebProxy("192.168.0.2:80", true);
                // proxy.Address = new Uri("");//按配置文件创建Proxy 地置
                //proxy.Credentials = new NetworkCredential("用户名", "密码");//从配置封装参数中创建
                //objRequest.Proxy = proxy; 

                HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

                Stream objStream = objResponse.GetResponseStream();
                StreamReader objReader = new StreamReader(objStream, Encoding.GetEncoding(com.PageEnCode));
                LOGIN_RES=objReader.ReadToEnd();
                if (LOGIN_RES != null) LOGIN_RES = LOGIN_RES.Trim();
                objReader.Close();
                objStream.Close();

                return LOGIN_RES;

            }
            catch (Exception ex){
                Console.Write(ex.Message);
                return null;

            }

        }

2、程序升级

利用1里面的方法,读取服务器某网页文件,获取版本号和当前程序版本进行比较,若有最新版,

则在WM里打开浏览器进行下载:

private void checkUpdate()
        {
            int k = comHTTP.AutoUpdate();
            if (k > com.COPYRIGHT)
            {
                MessageBox.Show("\r\n系统监测到新版本,程序将自动打开下载,请安装后继续使用.\r\n\r\n", "提示");
                System.Diagnostics.Process.Start("IEXPLORE.EXE", "/autoupdate.cab");//打开IE,
                Application.Exit();

            }
        }
20109 月17

Java ME/J2ME 环境搭建、WM6.1运行JBED虚拟机手机实现JSR179定位

接触Java ME,到现在已经过去五天了。利用一款带GPS模块的WM6.1系统的手机实现定位和数据上报项目,周期为18天,公司没有一个人搞过手机开发,囧,身为研发部负责人责无旁贷(目前是光杆司令)……

废话不多讲,刚开始用MyEclispe + MyEclispeMe + WTK + JDK 搭建了开发环境(这也是费了九牛二虎之力)

一、Java ME/J2ME环境的搭建

1、安装 MyEclipse

MyEclipse_6.5.1GA_E3.3.2_Installer.exe、myEclipse6.5汉化包.rar、MyEclipse注册码.txt

2、安装 MyEclispeMe 开发插件

运行MyEclispe –>帮助–>Software Updates–>Find and Install –>搜索新部件

新建站点:http://eclipseme.org/updates/ (可能要翻翻哦),确定,全部勾选,安装,完毕。

3、安装 JDK

JDK6.0.21版本,如果找不到就先安装 jdk-6u20-windows-i586.exe 再打21补丁 JavaSetup6u21.exe。

4、安装 JavaME SDK

sun_java_me_sdk-3_0-win.exe

5、安装 WTK

WTK2.5.2_01版本,sun_java_wireless_toolkit-2.5.2_01-win.exe

MyEclispe–>首选项–>J2ME–>设备管理–>选择WTK目录–>refresh

(以上这些软件你就百度吧,不行就google,再不行必应)

注意:MyEclipse 编译的JAR包,很可能在虚拟机上安装不了。提示什么907啊,30的错误。

解决办法就是打开,JAR,编辑META-INF文件夹下的 MANIFEST.MF 文件,增加一行:

MIDlet-1: Test,,demo.LocationMIDlet  名字为Test,入口类为demo.LocationMIDlet

有的环境可能需要JAD包,相应的里面也要加上这一行。

二、支持JSR179的虚拟机

WM6.1上安装4EsmertecJbed_v20090217.5.1a_Chs.cab,狗狗搜,搜不到就找我要吧。

三、测试代码

package demo;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.location.Coordinates;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;
//import javax.microedition.location.QualifiedCoordinates;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class LocationMIDlet extends MIDlet implements CommandListener, Runnable
{
    private Display myDisplay;
    private Command okcmd;
    private Command ecmd;
    private Form form;
    private List myList;
    private boolean yes;

    public LocationMIDlet()
    {
        myDisplay = Display.getDisplay(this);
        myList = new List("测试真机是否支持 JSR179", List.IMPLICIT);
        okcmd = new Command("测试", Command.OK, 1);
        ecmd = new Command("退出", Command.OK, 1);
        form = new Form("GPS");
        String cellid=System.getProperty("CellID");
        if(cellid==null||"".equals(cellid)){
        	cellid=System.getProperty("Cell-ID");
        }
        if(cellid==null||"".equals(cellid)){
        	cellid=System.getProperty("CELLID");
        }
        if(cellid==null||"".equals(cellid)){
        	cellid=System.getProperty("CELL-ID");
        }
        form.append("CellID:"+cellid);
        form.append("JSR:"+System.getProperty("Version"));
        myList.addCommand(okcmd);
        form.addCommand(ecmd);
        form.setCommandListener(this);
        myList.setCommandListener(this);
    }
    protected void destroyApp(boolean arg0)
            throws MIDletStateChangeException {}
    protected void pauseApp(){}
    protected void startApp() throws MIDletStateChangeException
    {
        myDisplay.setCurrent(myList);
    }
    public void commandAction(Command arg0, Displayable arg1)
    {
    	if(arg0 == okcmd)
        {
            String version = System.getProperty("microedition.location.version");
            yes = (version != null && !version.equals(""));
            Thread t = new Thread(this);
            t.start();
        }
    	if(arg0 == ecmd)
        {
           this.notifyDestroyed();
        }
    }
    public void run()
    {
    	myDisplay.setCurrent(form);
        //测试真机是否支持 jsr179
        if(yes)
        {
            // Set criteria for selecting a location provider:
            // accurate to 500 meters horizontally
            // 设置精度
            Criteria myCriteria = new Criteria();
            myCriteria.setHorizontalAccuracy(500);

            double lat = 0;
            double lon = 0;

            // Get an instance of the provider
            // 找卫星,找服务
            try
            {
                LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);

                // Request the location, setting a one-minute timeout
                // 请求位置,并设置超时时间
                Location myLocation = myLocationProvider.getLocation(5000);
                Thread.sleep(1000);
                Coordinates myCoordinates = myLocation.getQualifiedCoordinates();
                for(int i=0;i<10;i++){
                if(myCoordinates != null)
                {
                    // Use coordinate information
                    // 得到经纬度
                    lat = myCoordinates.getLatitude();
                    lon = myCoordinates.getLongitude();
                }

                form.append("真机支持JSR179,纬度坐标:" + String.valueOf(lat) + ",经度坐标:" + String.valueOf(lon));

                form.append("------------"+i);

                try{
                    Thread.sleep(1000);
                    }catch(Exception e){

                    }
                }
            }
            catch (LocationException e)
            {
            	form.append("LocationException 发生异常");
                e.printStackTrace();
            } catch (InterruptedException e)
            {
            	form.append("InterruptedException 发生异常");
                e.printStackTrace();
            }

        }
        //真机不支持 jsr179
        else
        {
        	form.append("真机不支持JSR179");

        }

    }

}

四、遗留问题

WM6.1手机系统运行JBED虚拟机上的Java ME软件,通过JSR179获取经纬度已实现。
(先运行WM上的GPS软件,后执行虚拟机里的测试代码)
两个问题:
1、室内等信号弱的地方无法定位;
2、JSR179是否需要WM上的程序进行GPS初始化待验证。
初步验证失败,貌似需要WM上先初始化GPS拨号找到卫星,虚拟机里程序才能读取数据,杯具。。。
再研究研究。。。