2011十二月22
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);
}
}
2011十二月12
合肥UI设计交流群:74602525
合肥UI设计、美工、Flash制作、图片美化、PS等交流群。
努力搭建本地UI外包交易交流群。
2011十一月23
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 里面修改验证不通过要跳转的页面,页面上会打印一些参数)
2011九月6
网页中实现自动上传本地文件,而不需要用户选择,这种应用场景很多,例如业务系统中需要使用的二代身份证扫描器、一体机(扫描仪)、摄像头拍照等。
首先介绍一个国外网站: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截图,自动把文件上传到服务器,于是联系作者。作者是个好人哈,分享了一些经验甚至代码。目前在作者的帮助下,已实现的网页控件的文件自动上传功能,可传多个文件、多表单项。
下面要解决如何在线安装的问题了……
2011八月31
<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>
2011七月31
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;
}
}
}
2011七月15
最近被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。
2011五月28
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();
}
}
2011五月19
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;
}
}
});
}
}
2011五月19
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);
}
}