‘编程学习’ 分类下的所有文章
20127 月31

JS:实现复选框上下级联动

function sel(obj){
         var id=obj.value;
         var qx=document.getElementsByName("id");
         for(var i = 0; i < qx.length; i ++)
           {
               if(qx[i].type == "checkbox")
                {
                  var v=qx[i].value;
                  if(v!=""&&v.length>id.length&&v.startWith(id)){
                      if(obj.checked){
                          qx[i].checked=true;
                      } else{
                           qx[i].checked=false;
                      }
                  }
                   if(v!=""&&v.length<id.length&&id.startWith(v)){
                      if(obj.checked){
                      } else{
                           qx[i].checked=false;
                      }
                  }

                }
           }
<input onclick="sel(this)" type="checkbox" name="id" value="0001" />0001

<input onclick="sel(this)" type="checkbox" name="id" value="00010001" />00010001

<input onclick="sel(this)" type="checkbox" name="id" value="00010002" />00010002

<input onclick="sel(this)" type="checkbox" name="id" value="00010003" />00010003
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());//自己重构的日志方法
20125 月16

SQL语句:查询1公里范围内经纬度数据

查询1公里范围内的经纬度数据:

select 6371.012 *
       acos(cos(acos(-1) / 180 * d.LATITUDE) *
            cos(acos(-1) / 180 * 31.885972440801) *
            cos(acos(-1) / 180 * d.LONGITUDE - acos(-1) / 180 * 117.30923429642) +
            sin(acos(-1) / 180 * d.LATITUDE) *
            sin(acos(-1) / 180 * 31.885972440801))*1 as a,
       id,name 
  from loc_data d
 where 6371.012 *
       acos(cos(acos(-1) / 180 * d.LATITUDE) *
            cos(acos(-1) / 180 * 31.885972440801) *
            cos(acos(-1) / 180 * d.LONGITUDE - acos(-1) / 180 * 117.30923429642) +
            sin(acos(-1) / 180 * d.LATITUDE) *
            sin(acos(-1) / 180 * 31.885972440801))*1 < 1 order by a asc
20123 月2

MyEclispe 9.1 注册码

MyEclispe 9.1 注册:

http://www.lephones.info/servlet/MyEclipseGenServlet

Subscriber:wizzer

Subscription Code:jLR8ZC-855550-60585657570866770

20121 月31

解决思路:通过百度地图JS API将经纬度反解析为位置信息

使用百度地图JS API,制作一个自刷新页面,将从数据库查询出的经纬度作为一个坐标点传给百度API JS,当获得位置信息后执行JS里的AJAX方法访问另外一个页面,将地址保存入库。 

<script language=”JavaScript”>function myrefresh(){ window.location.reload(force=true);}setTimeout(‘myrefresh()’,1000);</script>

————————————————–

window.location.reload(force=true)

绕过缓存,从服务器下载文档。

window.location.reload(force=false)

这个是默认的,检测服务器上文档是否改变,如没有改变,就从缓存调出。

 

ps:因google反地址解析API有频率限制,所以只好用百度地图了,没有找到百度地图URL形式的API,只能另辟蹊跷。:)

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);
	}
}
201112 月12

合肥UI设计交流群:74602525

合肥UI设计交流群:74602525

合肥UI设计、美工、Flash制作、图片美化、PS等交流群。

努力搭建本地UI外包交易交流群。

201111 月23

JAVA Oauth 认证服务器的搭建

1、软件下载

Oauth服务端: http://code.google.com/p/oauth/  通过SVN,下载源码。

                          或者下载站长整合好的示例源码:http://115.com/file/aqvpzqhz

客户端下载:http://code.google.com/p/oauth-signpost/  oauth-signpost

                         或者下载站长整合好的示例源码:http://115.com/file/bhy1d2ce

2、服务端源码下载后,把相关代码整合在一起(或直接下载站长整合好的代码),修改net.oauth.provider.core.SampleOAuthProvider  类,把从 provider.properties 读取的信息改为从数据库中读取,如APP_KEY、APP_SCERET、描述、回调地址。

3、net.oauth.example.provider.servlets下面的四个类,这里对应着oauth3个请求url,跟一个用于测试的链接,可以根据需求修改,如将调用Oauth的用户信息记录下来。

4、修改web.xml 增加三个请求url

<servlet>
		<servlet-name>request_token</servlet-name>
		<servlet-class>net.oauth.provider.servlets.RequestTokenServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>request_token</servlet-name>
		<url-pattern>/oauth/request_token</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>access_token</servlet-name>
		<servlet-class>net.oauth.provider.servlets.AccessTokenServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>access_token</servlet-name>
		<url-pattern>/oauth/access_token</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>authorize</servlet-name>
		<servlet-class>net.oauth.provider.servlets.AuthorizationServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>authorize</servlet-name>
		<url-pattern>/oauth/authorize</url-pattern>
	</servlet-mapping>

5、做个拦截器,只要通过某url访问的都需要进行Oauth认证:

web.xml

<filter>
	   <filter-name>OauthFilter</filter-name>
	   <filter-class>web.school.phone.OauthFilter</filter-class>
	</filter>
	<filter-mapping>
	   <filter-name>OauthFilter</filter-name>
	   <url-pattern>/phone/*</url-pattern>
	</filter-mapping>

 web.school.phone.OauthFilter

	package web.school.phone;
         import java.io.IOException;

	import javax.servlet.Filter;
	import javax.servlet.FilterChain;
	import javax.servlet.FilterConfig;
	import javax.servlet.ServletException;
	import javax.servlet.ServletRequest;
	import javax.servlet.ServletResponse;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	import net.oauth.OAuthAccessor;
	import net.oauth.OAuthMessage;
	import net.oauth.provider.core.SampleOAuthProvider;
	import net.oauth.server.OAuthServlet;

	public class OauthFilter implements Filter {

	  public void destroy() {
	  }

	  public void init(FilterConfig fConfig) throws ServletException {
	  }

	  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	  throws IOException, ServletException {
	    HttpServletRequest req=(HttpServletRequest)request;
	    HttpServletResponse res=(HttpServletResponse)response;

	    try{
            OAuthMessage requestMessage = OAuthServlet.getMessage(req, null);
            OAuthAccessor accessor = SampleOAuthProvider.getAccessor(requestMessage);
            SampleOAuthProvider.VALIDATOR.validateMessage(requestMessage, accessor);

            System.out.println("[OauthFilter:passed]:"+req.getRequestURI());
            chain.doFilter(request, response);//验证通过则转向

        } catch (Exception e){
        	//验证不通过
            SampleOAuthProvider.handleException(e, req, res, false);
        }

	  }

}

6、执行客户端代码,提示输入验证码时,把控制台打印的URL放到浏览器里打开,输入授权码:

(服务端AuthorizationServlet 里面修改验证不通过要跳转的页面,页面上会打印一些参数)

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 月18

Android:实用代码(开启启动、建立GPRS连接、闹钟等)

1:查看是否有存储卡插入

String status=Environment.getExternalStorageState();
if(status.equals(Enviroment.MEDIA_MOUNTED))
{
说明有SD卡插入
}

2:让某个Activity透明

OnCreate中不设Layout
this.setTheme(R.style.Theme_Transparent);

以下是Theme_Transparent的定义(注意transparent_bg是一副透明的图片)

3:在屏幕元素中设置句柄

使用Activity.findViewById来取得屏幕上的元素的句柄. 使用该句柄您可以设置或获取任何该对象外露的值.
TextView msgTextView = (TextView)findViewById(R.id.msg);
msgTextView.setText(R.string.push_me);

4:发送短信

String body=”this is mms demo”;

Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”smsto”, number, null));
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);
startActivity(mmsintent);

5:发送彩信

StringBuilder sb = new StringBuilder();

sb.append(”file://”);

sb.append(fd.getAbsoluteFile());

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”mmsto”, number, null));
// Below extra datas are all optional.
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);

startActivity(intent);

6:发送Mail

mime = “img/jpg”;
shareIntent.setDataAndType(Uri.fromFile(fd), mime);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

shareIntent.putExtra(Intent.EXTRA_TEXT, body);

7:注册一个BroadcastReceiver

registerReceiver(mMasterResetReciever, new IntentFilter(”OMS.action.MASTERRESET”));

private BroadcastReceiver mMasterResetReciever = new BroadcastReceiver() {

public void onReceive(Context context, Intent intent){
String action = intent.getAction();
if(”oms.action.MASTERRESET”.equals(action)){
RecoverDefaultConfig();
}
}

};

8:定义ContentObserver,监听某个数据表

private ContentObserver mDownloadsObserver = new DownloadsChangeObserver(Downloads.CONTENT_URI);

private class DownloadsChangeObserver extends ContentObserver {
public DownloadsChangeObserver(Uri uri) {
super(new Handler());

}

@Override
public void onChange(boolean selfChange) {}
}

9:获得 手机UA

public String getUserAgent()
{
String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);
return user_agent;
}

10:清空手机上Cookie

CookieSyncManager.createInstance(getApplicationContext());
CookieManager.getInstance().removeAllCookie();

11:建立GPRS连接

//Dial the GPRS link.
private boolean openDataConnection() {
// Set up data connection.
DataConnection conn = DataConnection.getInstance();

if (connectMode == 0) {
ret = conn.openConnection(mContext, “cmwap”, “cmwap”, “cmwap”);
} else {
ret = conn.openConnection(mContext, “cmnet”, “”, “”);
}

}

12:PreferenceActivity 用法

public class Setting extends PreferenceActivity

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}

Setting.xml:

Android:key=”seting2″
android:title=”@string/seting2″
android:summary=”@string/seting2″/>

android:key=”seting1″
android:title=”@string/seting1″
android:summaryOff=”@string/seting1summaryOff”
android:summaryOn=”@stringseting1summaryOff”/>

13:通过HttpClient从指定server获取数据

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(“http://www.baidu.com/1.html”);
HttpResponse resp;
Reader reader = null;
try {
// AllClientPNames.TIMEOUT
HttpParams params = new BasicHttpParams();
params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
httpClient.setParams(params);
resp = httpClient.execute(method);
int status = resp.getStatusLine().getStatusCode();

if (status != HttpStatus.SC_OK) return false;

// HttpStatus.SC_OK;
return true;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null) try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

14:显示toast

Toast.makeText(this._getApplicationContext(), R.string._item, Toast.LENGTH_SHORT).show();

15:屏幕显示

程序中默的显示是带有标题栏和系统信息栏的,有的时候,这很影响程序界面的美观。手机默认的是竖屏,或与感应器状态相关,为了某种效果,我们的程序需要限制使用横屏或竖屏。以下的代码就解决了上述问题。

//设置为无标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
//设置为全屏模式
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//设置为横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

16:Intent传参

当Activity与Activity/Service(或其它情况)有时与要进行参数传递,最常用也是最简单的方式就是通过Intent来处理。
看如下代码:
Intent intent = new Intent(…);
Bundle bundle = new Bundle();
bundle.putString(“NAME”, “zixuan”);
intent.putExtras(bundle);
context.startActivity(intent); 或 context.startService(intent);

当然,有传送就有接收,接收也很简单,如:
Bundle bunde = intent.getExtras();
String name = bunde.getInt(“NAME”);
当然参数KEY要与传送时的参数一致。

17:获取手机号

在j2me中,根本没有办法获取用户的手机号码,就连获取手机串号(IMEI)都基本上无法实现,然后在android手机上一切都是如此的简单,看代码:
TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String imei = tm.getDeviceId();
String tel = tm.getLine1Number();
看来,android的确加速了j2me的消亡。

18:振动器

总感觉手机上的振动器没有多大用处(当然静音模式下的振铃很有用),但还是顺带着说一下吧,只有两行代码:
1、获取振动服务的实例
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
2、设置振动时长,单位当然也是ms
vibrator.vibrate(1000);
如果你觉得这样过去单调的话,可以设个节奏:
vibrator.vibrate(new long[]{10, 100, 20, 200}, -1);
两个参数,习惯告诉我第一个是节奏,第二个是重复次数,可事实并没有这么简单,我翻译不好,大家还是看原文吧:
public void vibrate (long[] pattern, int repeat)
pattern: an array of longs of times to turn the vibrator on or off.
repeat: the index into pattern at which to repeat, or -1 if you don’t want to repeat.
google喜欢弄些技巧,我却觉得这里有点弄巧成拙了。

19:闹钟管理

最近看了一下Android的闹钟管理类(AlarmManager),真不错误,强大又简单,代码如下:

1)、建立一个AlarmReceiver继承入BroadcastReceiver,并在AndroidManifest.xml声明
public static class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, “闹钟提示:时间到!”, Toast.LENGTH_LONG).show();
}
}

2)、建立Intent和PendingIntent,来调用目标组件。
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

3)、设置闹钟
获取闹钟管理的实例:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
设置单次闹钟:
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5*1000), pendingIntent);
设置周期闹钟:
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10*1000), (24*60*60*1000), pendingIntent);

20:开机自启动

1).定义一个BroadcastReceiver

public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent intent) {
Log.d(“BootReceiver”, “system boot completed”);
//start activity
String action=”android.intent.action.MAIN”;
String category=”android.intent.category.LAUNCHER”;
Intent myi=new Intent(ctx,CustomDialog.class);
myi.setAction(action);
myi.addCategory(category);
myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(myi);
//start service
Intent s=new Intent(ctx,MyService.class);
ctx.startService(s);
}
}

2).配置Receiver的许可,允许接收系统启动消息,在AndroidManifest.xml中:

3).配置Receiver,可以接收系统启动消息,在AndroidManifest.xml中






4).启动模拟器,可以看到系统启动后,弹出一个对话框。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lxh2808/archive/2010/10/30/5976351.aspx

20115 月13

杯具程序员

上联:为系统而生,为框架而死,为debug奋斗一辈子。
下联:吃符号的亏,上大小写的当,最后死在需求上!
横批:杯具程序员。

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());
	}

}
20115 月4

合肥 Android/Java开发交流群:26310065

手机开发:WM、Android、iOS
WEB开发:Java、.NET、ASP、PHP、JSP
应用开发:C#、JAVA……

欢迎IT从业人士加入,交流开发经验、技术,项目外包等信息。
QQ群:26310065