2024年3月13日发(作者:)
工具
// 创建文件,参数包括路径(不能为空),文件名称,内容
publicstaticvoidmakefile(String path, String filename, String
content) {
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
tackTrace();
if (fos != null) {
}
try {
}
();
();
// TODO: handle exception
}
fos = newFileOutputStream(newFile);
(es());
File dir = newFile(path);
if (!()) {
}
();
File newFile = null;
if(path!=null){
();
//
newFile = newFile(olutePath()+"/"+filename);
FileOutputStream fos = null;
try {
NewFile();
if (() && te()) {
} finally {
} catch (IOException e) {
2.下载图片工具
publicclassDownloadPicUtil{
*
*@paramurl
*@paramfilename
*@return0没有图片;return1成功;return2IO异常;
*/
publicstaticintDownLoadBitmap(String url,Stringfilename) {
// TODO Auto-generated method stub
InputStream inputStream= null;
DefaultHttpClient client = newDefaultHttpClient();
try {
HttpGet request=newHttpGet(url);
HttpResponse response=e(request);
if(statusCode!=_OK){
}
// TODO Auto-generated catch block
tackTrace();
return 2;
if(inputStream!=null){
}
try {
}
();
// TODO Auto-generated catch block
tackTrace();
} catch (IOException e) {
return 1;
return 0;
HttpEntity entity =ity();
inputStream = tent();
Bitmap bitmap = Stream(inputStream);
//图片可以在这个时候存储到sdcard上
saveBitmap(bitmap,filename);
}else{
int statusCode = tusLine().getStatusCode();
/**
}catch (Exception e) {
}finally{
}
}
}
publicstaticvoidsaveBitmap(Bitmap bitName,String filename) {
}
String filepath = "/sdcard/baomi/";
File f = newFile(filepath+filename);
FileOutputStream fout = null;
try{
}
NewFile();
fout = newFileOutputStream(f);
ss(,100,fout);
();
();
tackTrace();
}catch(Exception e){
请求工具
publicclassHttpUtil{
publicstaticStringSESSION_ID=null;
publicstaticHttpResponsegetHttpResponse(HttpGet request) throws
BasicHttpParams httpParams = newBasicHttpParams();
tance().recordLog("进入getHttpResponse");
nectionTimeout(httpParams,
ctionTimeout);
ClientProtocolException,IOException{
tance().recordLog("超时时间为:
"+ctionTimeout);
imeout(httpParams,
tance().recordLog("Socket超时时间为:
eout);
"+eout);
DefaultHttpClient httpClient = newDefaultHttpClient(httpParams);
}
publicstaticHttpResponsegetHttpResponse(HttpPost request) throws
BasicHttpParams httpParams = newBasicHttpParams();
nectionTimeout(httpParams,
ctionTimeout);
imeout(httpParams,
tance().recordLog("获得响应客户端");
HttpResponse response=e(request);
tance().recordLog("获得结果");
nectionManager().shutdown();
tance().recordLog("关闭连接");
return response;
ClientProtocolException,IOException{
eout);
DefaultHttpClient httpClient = newDefaultHttpClient(httpParams);
}
//通过url发送post请求,并返回结果
publicstaticStringqueryStringForPost(String url){
tance().recordLog("发送POST请求");
HttpPost request = newHttpPost(url);
String result=null;
try {
HttpResponse response=pResponse(request);
HttpResponse response=e(request);
nectionManager().shutdown();
return response;
tance().recordLog("POST返回状态为
"+tusLine().getStatusCode());
if(tusLine().getStatusCode()==200){
}
result=ng(ity());
return result;
} catch (Exception e) {
tance().recordLog("POST异常:
"+sage());
tackTrace();
result="网络异常";
return result;
tance().recordLog("发送GET请求");
String result=null;
try {
ResponseHandler
HttpClient httpclient = newDefaultHttpClient();
tance().recordLog("提交的地址为:"+url);
HttpGet httpget = newHttpGet(url);
result = e(httpget, responseHandler);
tance().recordLog("GET返回状态为"+result);
return result;
}
//通过url发送GET请求并返回结果
publicstaticStringqueryStringForGet(String url){
}
returnnull;
newBasicResponseHandler();
} catch (Exception e) {
tance().recordLog("GET异常:
"+sage());
tackTrace();
result="网络异常";
return result;
}
//通过HttpPost发送POST请求,并返回结果
publicstaticStringqueryStringForPost(HttpPost request){
String result=null;
try {
HttpResponse response=pResponse(request);
if(tusLine().getStatusCode()==200){
}
result=ng(ity());
return result;
}
} catch (Exception e) {
tackTrace();
result="网络异常";
return result;
}
}
}
returnnull;
工具
public class JSonUtil {
public static String string2json(String s){
StringBuilder sb = new StringBuilder(()+20);
('"');
for (int i=0;i<();i++){
char c =(i);
switch(c){
case '"':
}
(""");
break;
("");
break;
("");
break;
("b");
break;
("f");
break;
("n");
break;
("r");
break;
("t");
break;
default:
(c);
case '':
case '/':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
}
('"');
return ng();
}
public static String number2json(Number number){
return ng();
}
public static String boolean2json(Boolean bool){
return ng();
}
public static String map2json(Map map){
if(y()){
}
StringBuilder sb = new StringBuilder(()<<4);
("{");
Set
for(String key :keys){
}
rAt(()-1, '}');
return ng();
}
public static String array2json(Object[] array){
if(==0){
}
StringBuilder sb = new StringBuilder(<<4);
("[");
for(Object o:array){
}
rAt(()-1, ']');
(tojson(o));
(',');
return "[]";
Object value = (key);
('"');
(key);
('"');
(":");
(tojson(value));
(',');
return "[]";
return ng();
}
public static String tojson(Object o){
if(o==null)
if(o instanceof String)
if(o instanceof Boolean)
if(o instanceof Map)
return map2json((Map)o);
return array2json((Object[])o);
new RuntimeException("Unsupported
if(o instanceof Object[])
throw
}
/*Servlet 输出json
tentType("application/json;charset=UTF-8");
racterEncoding("UTF-8");
PrintWriter pw = ter();
((obj));
();
*/
}
return boolean2json((Boolean)o);
return number2json((Number)o);
if(o instanceof Number)
return string2json((String)o);
return "null";
type :"+ss().getName());
encode 转ucs2码双字节
publicclassStringUtil {
publicstaticStringStringToHex(String input) {
String result = "";
if (input != null) {
byte[] bytes = null;
try {
bytes = es("UTF-16BE");
}
}
}
} catch (Exception e) {
}
StringBuffer reValue = newStringBuffer();
StringBuffer tem = newStringBuffer();
for (int i = 0; i < ; i++) {
}
result = ng().toUpperCase();
return result;
return"";
(0, ());
(tring(bytes[i] & 0xFF));
if (() == 1) {
}
(tem);
(0, '0');
// TODO Auto-generated catch block
returnnull;
} else {
publicstaticStringHexToUTF16BE(String input) {
}
Stringresult = "";
if (input != null) {
}
byte[] bytes1 = newbyte[() / 2];
for (int i = 0; i < (); i += 2) {
}
try {
}
return result;
return "";
result = newString(bytes1, "UTF-16BE");
// TODO Auto-generated catch block
return null;
} catch (UnsupportedEncodingException e) {
bytes1[i / 2] = (byte)
i + 2), 16));
(nt(ing(i,
} else {
cation实例
NotificationManager
notificationManager=(NotificationManager)temService(NOTIFICATION_SERVICE);
//定义一个Notification
Notification m_notification = newNotification();
//设置Notification的各种属性
//设置通知在状态栏的图标
m_ = ;
//当我们点击通知时显示的内容
m_Text = "BUTTON1通知内容";
//通知时发出的默认声音
m_ts = T_SOUND;
//设置通知显示的参数
Intent intent = newIntent();
PendingIntent m_pendingIntent =
ivity(,0,intent,0);
m_estEventInfo(,"BUTTON",
//开始执行通知
i++;
(i,m_notification);
"BUTTON1通知内容",m_pendingIntent);
L Theard
publicclassPostThreadextendsThread {
privatestaticContextcontext;
privatePostURL[] posturls;
privateHttpResponsehttpResponse;
privateDefaultHttpClient httpClient;
privateHttpPost httpRequest;
privatestaticBasicHttpParamshttpParams;
privatestaticPostURLAdapteradapter;
privateString[] sparams ;
privateString[] sfiles;
privateList
/* 允许Input、Output,不使用Cache */
nectTimeout(ctionTimeout);
dTimeout(leTimeout);
nput(true);
utput(true);
Caches(false);
/* 设置传送的method=POST */
uestMethod("POST");
/* setRequestProperty */
uestProperty("Connection", "keep-alive");
uestProperty("Charset", "UTF-8");
uestProperty("Content-Type",
String end = "rn";
String prefix = "--";
try {
URL url = newURL(posturl);
HttpURLConnection con = (HttpURLConnection)
StringBuilder sb = newStringBuilder();
FileInputStream fStream=null;
String boundary = "*****";
publicPostThread(Context context) {
}
publicstaticintPostWithFile(String posturl,Map
super();
t = context;
adapter = newPostURLAdapter(context);
();
httpParams = newBasicHttpParams();
nectionTimeout(httpParams,
ctionTimeout);
imeout(httpParams,
httpClient = newDefaultHttpClient(httpParams);
eout);
postparam,Map
nnection();
"multipart/form-data;boundary=" + boundary);
//
{
// 拼接参数(不包括文件)
List
for (
(prefix);
(boundary);
(end);
("Content-Disposition:form-data;name="" +
+
newArrayList
()
"""+end+"Content-Type:text/plain;Charset=UTF-8"+end );
if(("0")){
("Content-Transfer-Encoding:8bit"+end+end+
ue() + end);
}else{
("Content-Transfer-Encoding:8bit"+end+end+
((ue()==null||ue().equals(""))?
ingToHex(""):ToHex(ue())) + end);
//
{
sb = newStringBuilder();
(prefix);
(boundary);
(end);
("Content-Disposition:form-data;name=""
+ ()
+ "";filename=""
+ ue().substring(
/* 设置DataOutputStream */
DataOutputStream ds =
Stringt=ng();
(ng().getBytes());
//发送文件
for (
}
}
newDataOutputStream(putStream());
//
ue().lastIndexOf('/') + 1) +
"""
+ end);
("Content-Type:application/octet-stream;Charset=UTF-8"
}
//表单结束标志
(prefix);
(boundary);
(prefix);
(end);
(ng().getBytes());
+ end + end);
(ng().getBytes());
/* 取得文件的FileInputStream */
fStream = newFileInputStream(ue());
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = newbyte[bufferSize];
int size = 0;
int length = 0;
/* 从文件读取数据至缓冲区 */
while ((length = (buffer)) != -1) {
}
sb = newStringBuilder();
(end);
(ng().getBytes());
();
/* 将资料写入DataOutputStream中 */
(buffer, 0, length);
size = size + length;
/* close streams */
();
/* 取得Response内容 */
//
int res=ponseCode();
if(res!=200){
//由后台程序提交
tance().recordLog("存入数据库的提交地址为:
"+posturl+" n提交的数据为:"+(postparam)+" n附
件:"+(postfile));
}
//网络连接超时
putTODB(posturl, postparam,postfile, type);
putTODB(posturl, postparam,postfile, type);
// ();
();
nect();
return 1;
if(!("0")){//编码
}
String s ="";
InputStreamReader isr =
int i ;
while((i=())!=-1){
s=s+(char)i;
}
}else{
newInputStreamReader(utStream(),"UTF-8");
String result =(s);
();
nect();
if(("0")){
}
//不编码方式
return 10;
//提交成功
return 0;
//服务端提交没有成功
return -1;
}else{
}else{
}catch(SocketTimeoutException cone){
}
}
return -2;
catch (Exception e) {
}
return -1;
privatestaticvoidshowDialog(String mess)
{
r(context).setTitle("来自服务器的消息")
.setMessage(mess)
.setNegativeButton("确定",kListener()
{
publicvoidonClick(DialogInterface dialog, int which)
{
}
})
.show();
}
/**
*向服务器发送请求,如果发送不成功,将会自动存入到数据库中,由线程在后台自动提交
*@paramposturl要提交数据的url地址,如
192.168.31.15:8080/TDDemonstration/?method=addEv
ent
*@parampostparam要提交的form中的参数(名值对)
*@parampostfile要提交的form中的文件参数(form中控件名,上传的文件路径全名名
*@paramtype暂时设置为"1",为保证紧急消息最先执行数值越大表示越紧急;(0为向蒋
*@return0数据发送成功1数据发送不成功,由后台线程去自动提交-1提交出现异常
*/
publicstaticsynchronizedintPost(String posturl,Map
值对)
勇的工程提交)
postparam,Map
//检查网络状态
if(!kIsOK){
putTODB(posturl, postparam,postfile,type);
return 2;
if(postfile==null||y()){//不带附件
returnpostNotWithFile(posturl, postparam,
}else{
postfile,type);
// 发送不成功,存入数据库中
if (tusLine().getStatusCode() != 200) {
tance().recordLog("存入数据库的提交地址为:
}
privatestaticintpostNotWithFile(String posturl,
Map
}
}else{
}
//带有附件
returnPostWithFile(posturl, postparam, postfile,type);
postfile,String type) {
DefaultHttpClient httpClient =
HttpPost httpRequest = newHttpPost(posturl);
List
for (
}
try {
httpRequest
.setEntity((HttpEntity) newUrlEncodedFormEntity(
localparams, _8));
if(("0")){//不编码
(newBasicNameValuePair((),
}else{//编码
(newBasicNameValuePair((),
}
.StringToHex(ue())));
newDefaultHttpClient(httpParams);
newArrayList
ue()));
StringUtil
HttpResponse httpResponse = e(httpRequest);
"+posturl+" n提交的数据为:"+(postparam)+" n附
件:"+(postfile));
putTODB(posturl, postparam,postfile, type);
// ();
return 1;
}
privatestaticvoidputTODB(String
}
catch(SocketTimeoutException cone){
}
catch (Exception e) {
}
// TODO Auto-generated catch block
tackTrace();
return -1;
//网络连接超时
putTODB(posturl, postparam,postfile, type);
return -2;
}
return 10;
}
} else {
// showDialog(result);
//解析返回的字符串编码
if(!("0")){//编码
String
result =(result);
if(("0")){
}
//提交成功
return 0;
//服务端提交没有成功
return -1;
result=ng(ity());
}else{
}else{//不编码
Stringresult=ng(ity());
posturl,Map
postfile,String type) {
PostURL aposturl = newPostURL();
}
if(type==null||("")){
}
a_type(type);
cute_status(0);
turl(posturl);
ams(postparam);
es(postfile);
e();
(aposturl);
type="0";
privatePostURL[] getData(){
ata("execute_status != 1", "data_type");
return ata("", "data_type"); //
}
publicvoidrun(){
while(true){
//检测网络状态是否可用
if(kIsOK ==true){
//检查是否有数据需要发送
//取出数据
posturls =getData();
if(posturls!=null){
//有附件
String end = "rn";
String prefix = "--";
try {
URL url = newURL(turl());
String boundary = "*****";
for(int i=0;i<;i++){
PostURL vo =posturls[i];
//将参数恢复成Map
();
if(es()!=null&&!es().isEmpty()){
HttpURLConnection con = (HttpURLConnection)
StringBuilder sb = newStringBuilder();
FileInputStream fStream=null;
/* 允许Input、Output,不使用Cache */
nnection();
nectTimeout(ctionTimeout);
dTimeout(leTimeout);
+
nput(true);
utput(true);
Caches(false);
/* 设置传送的method=POST */
uestMethod("POST");
/* setRequestProperty */
uestProperty("Connection",
uestProperty("Charset",
uestProperty("Content-Type",
// 拼接参数(不包括文件)
List
for (
(prefix);
(boundary);
(end);
"multipart/form-data;boundary=" +
"keep-alive");
"UTF-8");
boundary);
//
newArrayList
ams().entrySet()) {
("Content-Disposition:form-data;name="" + ()
"""+end+"Content-Type:text/plain;Charset=UTF-8"+end );
if(a_type().equals("0")){//不
编码
("Content-Transfer-Encoding:8bit"+end+end+
ue() + end);
}else{
//编码
("Content-Transfer-Encoding:8bit"+end+end+
((ue()==null||ue().equals(""))?
ingToHex(""):ToHex(ue())) + end);
//
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = newbyte[bufferSize];
int size = 0;
/* 取得文件的FileInputStream */
fStream =
+ end + end);
+ ()
+ "";filename=""
+ ue().substring(
+ end);
/* 设置DataOutputStream */
DataOutputStream ds =
Stringt=ng();
(ng().getBytes());
//发送文件
for (
sb = newStringBuilder();
(prefix);
(boundary);
(end);
}
}
newDataOutputStream(putStream());
es().entrySet()) {
("Content-Disposition:form-data;name=""
ue().lastIndexOf('/') + 1) + """
("Content-Type:application/octet-stream;Charset=UTF-8"
(ng().getBytes());
newFileInputStream(ue());
int length = 0;
/* 从文件读取数据至缓冲区 */
while ((length =
(buffer)) != -1) {
//
/* 将资料写入DataOutputStream中 */
(buffer, 0, length);
size = size + length;
}
sb = newStringBuilder();
(end);
();
}
//表单结束标志
(prefix);
(boundary);
(prefix);
(end);
(ng().getBytes());
/* close streams */
();
//
/* 取得Response内容 */
int res=ponseCode();
if(res!=200){
//不成功
cute_status(-1);
OneData((), vo);
();
nect();
}else{
OneData(());
();
nect();
}
}
catch(SocketTimeoutException cone){
//网络连接超时
}
catch (Exception e) {
//提交的表单有问题,为不让线程一直跑无效的数据,把
OneData(());
tackTrace();
该条记录删除
}
}else{
//没有附件
httpClient =
httpRequest = newHttpPost(turl());
List
for (
if(a_type().equals("0")){//不编码
newDefaultHttpClient(httpParams);
newArrayList
ams().entrySet()) {
(newBasicNameValuePair((),
}
try {
httpRequest
.setEntity((HttpEntity)
localparams,
}else{//编码
ue()));
(newBasicNameValuePair((), StringUtil
}
.StringToHex(ue())));
newUrlEncodedFormEntity(
_8859_1));
HttpResponse httpResponse =
e(httpRequest);
// 发送不成功,存入数据库中
if
(tusLine().getStatusCode() != 200) {
}
}
}
cute_status(-1);
OneData((), vo);
OneData(());
} else {
catch(SocketTimeoutException cone){
}
catch (Exception e) {
}
// TODO Auto-generated catch block
OneData(());
tackTrace();
//网络连接超时
}
}
}else{
//检查主应用程序是否退出了
if(vety!=true){
}
//线程结束发送数据,关闭数据库
();
break;
try {
}
(me);
// TODO Auto-generated catch block
tackTrace();
} catch (InterruptedException e) {
}else{
}
try {
}
}else{
(me);
// TODO Auto-generated catch block
tackTrace();
} catch (InterruptedException e) {
}
}
}
工具
publicclassIniReader {
}
}
(name, value);
name = ();
value = ();
int i = f('=');
String name = ing(0, i);
String value = ing(i + 1);
if (s(".*=.*")) {
privatevoidparseLine(String line) {
}
}
parseLine(line);
while ((line = ne()) != null) {
privatevoidread(BufferedReader reader) throws IOException {
String line;
}
BufferedReader reader = newBufferedReader(newInputStreamReader(
newFileInputStream(filename), "UTF-8"));
read(reader);
();
publicIniReader(String filename) throws IOException {
privateHashMap
}
}
if (value == null) {
}
return value;
return defalut;
publicStringgetValue(String name, String defalut) {
String value = (String) (name);
d数据库DBOpenhelper(数据库建在指定路径下)
helper
package ;
import fig;
import t;
import Database;
import OpenHelper;
import Factory;
public class DBOpenHelper extends SDSQLiteOpenHelper{
private static final int DB_VERSION =1;
private static final String DB_POSTURL_CREATE ="create table posturl
private static final String DB_NAME =_dictory;
private static final String DB_POSTURL_TABLE ="posturl";
(_id integer primary key autoincrement,data_type text,posturl
text,params text,files text,execute_status integer);";
private static final String DB_FAVOR_ADDRESS_CREATE ="create table
integer primary key autoincrement,x text,y favoraddress(_id
text,addressname text);";
private static final String DB_COMMANDTEMPLET_CREATE ="create table
commandtemplet (_id integer primary key autoincrement,made_time
text,templet_content_whole text,used_count integer,type integer);";
//命令表
/**
* (_id integer primary key autoincrement,主键
* command_id text, 服务器上的命令id号(本地拟制的命令不填写)
* establish_time text, 命令拟制时间
* command_establish_man_id text, 命令拟制人ID
* command_establish_man_name text,命令拟制人姓名
* command_establish_man_depart text, 命令拟制人部门
* command_establish_man_phone text, 命令拟制人电话
* command_receiver_man text,命令接收人(linkeman_id - type)
* command_content text,命令内容
* attach text, 附件地址(接收到的文件存放到/sdcard/td_pda/command目录
* posx text,命令发送时的地址
* posy text,命令发送时的地址
* type integer)类型 0:本地拟制的命令 1:接收到的命令
*/
private static final String DB_COMMAND_CREATE ="create table
"establish_time text,command_establish_man_id
text,command_establish_man_depart
text,command_receiver_man
text,posy text,type
下,所有的文件统一以数字(存储时的时间)命名)
command(_id integer primary key autoincrement,command_id text," +
text,command_establish_man_name
text," +
"command_establish_man_phone
text,attach text,command_content
integer);";
//任务反馈表
/**
* _id integer primary key autoincrement,主键
* feedback_id text,命令反馈的ID
* command_id text,命令的唯一标识(对应命令表的command_id)
* feedback_time text,反馈时间
* feedback_man_name text, 反馈人姓名(显示用,本地反馈时不填写)
* feedback_man_id text,反馈人ID号(在友邻表中的neighbor_id,供从地图上
* feedback_man_depart text,反馈人部门
* feedback_man_phone text,反馈人电话
* feedback_content text,反馈内容
* attach text,附件地址(接收到的文件存放到/sdcard/td_pda/feedback 目录
* posx text,反馈时的位置
* posy text,反馈时的位置
* type integer 类型 0:本地填写的反馈 1:接收到的任务反馈
*/
private static final String DB_FEEDBACK_CREATE ="create table
integer primary key autoincrement,feedback_id
text,posx
查看友邻的反馈情况使用)
下,所有的文件统一以数字(存储时的时间)命名)
feedback(_id
text,command_id text," +
"feedback_time text,feedback_man_name text,feedback_man_id
text,feedback_man_depart text,feedback_man_phone text,feedback_content
text,attach text,posx text,posy text,type integer);";
//事件表
/**
* _id integer primary key autoincrement,主键
* event_id text 事件ID
* event_report_man_id text 事件上报人ID
* event_report_man_name text 事件上报人(显示用),在本地上报事件时不填写
* event_report_man_depart text 事件上报人部门
* event_report_man_phone text,事件上报人电话号码,在本地上报事件时不填写
* event_title text ,事件标题
* event_content text, 事件内容
* report_time text, 事件上报时间
* attach text, 事件的附件(接收到的文件存放到/sdcard/td_pda/event 目录
* posx text,上报事件时的位置
* posy text,上报事件时的位置
* type integer 类型 0:本地上报的事件 1:接收到的事件
*/
private static final String DB_EVENT_CREATE ="create table event(_id
text,event_report_man_depart
text,event_title text,event_content
下,所有的文件统一以数字(存储时的时间)命名)
integer primary key autoincrement,event_id text, event_report_man_id
text,event_report_man_name
text,event_report_man_phone
//友邻表
/**
* _id integer primary key autoincrement,主键
* neighbor_id text,友邻id
* neighbor_name text,友邻名字
* neighbor_type text,友邻类型(1:单位 0:个人)
* neighbor_phone text,友邻的电话号码
* posx text,友邻位置(在地图上显示的友邻位置,友邻位置的变化由一个线程获取,
* posy text友邻位置(在地图上显示的友邻位置,友邻位置的变化由一个线程获取,
text,report_time text,attach text,posx text,posy text,type integer);";
获取到位置后存入该表中)
获取到位置后存入该表中)
*/
private static final String DB_NEIGHBOR_CREATE ="create table
integer primary key autoincrement,neighbor_id neighbor(_id
text,neighbor_name text,neighbor_type text,neighbor_phone text,posx
text,posy text);";
//通讯录表
/**
* _id integer primary key autoincrement,主键
* linkman_id text, 联系人ID号
* linkman_name text,联系人姓名
* parent text ,父亲ID
* linkman_type integer,联系人类型(1:单位 0:个人)
* phone text 联系人电话号码
*/
private static final String DB_LINKMAN_CREATE ="create table
integer primary key autoincrement,linkman_id linkman(_id
//公共信息表
/**
text,linkman_name text,parent text ,linkman_type integer,phone text);";
* _id integer primary key autoincrement,主键
* public_info_id text,公共信息ID号
* public_info_type text,公共信息类型
* public_info_title text,公共信息标题
* public_info_content text,公共信息内容
* public_info_origin text,公共信息来源
* attach_count integer 附件的数目(附件数目大于0时从publicinfoattach
表获取具体的附件内容)
*/
private static final String DB_PUBLIC_INFO_CREATE="create table
publicinfo(_id integer primary key autoincrement,public_info_id
text,public_info_type text,public_info_title text,public_info_content
text,public_info_origin text,attach_count integer);";
//公共信息附件表
/**
* _id integer primary key autoincrement,主键
* public_info_id text,公共信息ID号
* attach_name text,附件的名字
* attach_file text 附件文件的地址(接收到的文件存放到/
sdcard/td_pda/publicinfo 目录下,所有的文件统一以数字(存储时的时间)命名)
*/
private static final String DB_PUBLIC_INFO_ATTACH_CREATE="create
publicinfoattach(_id integer primary key
text,attach_name text,attach_file
table
text);";
public DBOpenHelper(Context context, String name,
}
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
autoincrement,public_info_id
@Override
public void onCreate(SQLiteDatabase _db) {
// TODO Auto-generated method stub
_L(DB_POSTURL_CREATE);
_L(DB_COMMANDTEMPLET_CREATE);
_L(DB_FAVOR_ADDRESS_CREATE);
_L(DB_COMMAND_CREATE);
_L(DB_FEEDBACK_CREATE);
_L(DB_EVENT_CREATE);
_L(DB_NEIGHBOR_CREATE);
_L(DB_LINKMAN_CREATE);
_L(DB_PUBLIC_INFO_CREATE);
_L(DB_PUBLIC_INFO_ATTACH_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion,
newVersion) {
// TODO Auto-generated method stub
_L("DROP TABLE IF EXISTS posturl");
_L("DROP TABLE IF EXISTS favoraddress");
_L("DROP TABLE IF EXISTS commandtemplet");
_L("DROP TABLE IF EXISTS command");
_L("DROP TABLE IF EXISTS feedback");
_L("DROP TABLE IF EXISTS event");
_L("DROP TABLE IF EXISTS neighbor");
_L("DROP TABLE IF EXISTS linkman");
_L("DROP TABLE IF EXISTS publicinfo");
_L("DROP TABLE IF EXISTS publicinfoattach");
onCreate(_db);
}
}
int
2. SDDBopenhelper
;
import fig;
t;
import Database;
Exception;
OpenHelper;
Factory;
;
publicabstractclassSDSQLiteOpenHelper {
privatestaticfinalStringTAG =
pleName();
privatefinalContextmContext;
privatefinalString mName;
privatefinalCursorFactory mFactory;
privatefinalint mNewVersion;
privateSQLiteDatabase mDatabase = null;
privateboolean mIsInitializing = false;
publicSDSQLiteOpenHelper(Context context, String name,
CursorFactory factory, int version) {
if(version<1 )thrownewIllegalArgumentException ("Version must
mContext = context;
mName = name;
mFactory = factory;
mNewVersion=version;
be >=1,was "+version);
}
publicsynchronizedSQLiteDatabasegetWritableDatabase(){
if(mDatabase !=null&&()&&!Only()){
}
if(mIsInitializing){
}
boolean success = false;
SQLiteDatabase db = null;
try{
mIsInitializing = true;
if(mName == null){
db = (null);
thrownewIllegalStateException("getWritableDatabase called
return mDatabase;
recursively");
}
}else{
}
int version = sion();
if(version!=mNewVersion){
}
onOpen(db);
success =true;
return db;
mIsInitializing = false;
if(success){
}
if(mDatabase!=null){
}
mDatabase=db;
if(db!=null) ();
try{
}
();
}catch(Exception e){
ransaction();
try{
}
if(version==0){
}
sion(mNewVersion);
nsactionSuccessful();
nsaction();
onCreate(db);
onUpgrade(db,version,mNewVersion);
}else{
String path = getDatabasePath(mName).getPath();
db=CreateDatabase(path, mFactory);
}finally{
}finally{
}else{
}
publicsynchronizedSQLiteDatabasegetReadableDatabase(){
if(mDatabase !=null&&()){
}
return mDatabase;
if(mIsInitializing){
}
if(mName == null) returnnull;
SQLiteDatabase db = null;
try{
}
mIsInitializing = true;
String path = getDatabasePath(mName).getPath();
db = tabase(path, mFactory,
if(sion()!= mNewVersion){
}
onOpen(db);
Log.w(TAG, "Opened "+mName+" in read-only mode");
mDatabase = db;
return mDatabase;
mIsInitializing= false;
if(db!=null&&db!=mDatabase) ();
thrownewSQLiteException("Can't upgrade read-only database
thrownewIllegalStateException("getReadableDatabase called
recursively");
_READWRITE);
from version "+sion()+" to "+mNewVersion +" : "+path);
}finally{
}
publicsynchronizedvoidclose(){
publicFilegetDatabasePath(String name){
returnnewFile("/sdcard/"+name);
}
publicabstractvoidonCreate(SQLiteDatabase db);
publicabstractvoidonUpgrade(SQLiteDatabase _db, int oldVersion, int
if(mIsInitializing) thrownewIllegalStateException ("Closed during
if(mDatabase!=null&&()){
}
();
mDatabase = null;
initialization");
}
newVersion) ;
publicvoidonOpen(SQLiteDatabase db){}
}
10.提示框
Builder builder = new r(this);
w(some_View);
itiveButton("查看",
kListener() {
}
publicvoidonClick(DialogInterface dialoginterface, int i) {
}).setNegativeButton("关闭",
kListener() {
publicvoidonClick(DialogInterface dialoginterface, int i) {
}
}).show();
11.读写操作
out = newFileOutputStream(file);
infoToWrite = infoToWrite+f(infro);
(es());
();
();
in = newFileInputStream(file);
byte[] temp = newbyte[ble()];
while ((temp)!=-1) {
}
display = newString(temp);
12.写日志实例
public class LogService {
private static String TAG ="LogService";
private SimpleDateFormat mylogsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static OutputStreamWriter writer;
private static LogService instance = null;
public static synchronized LogService getInstance()
{
if(instance == null)
{
try{
String Logpath =h;
//判断文件是否存在,不存则新建,存在就在文件后面追加日志
File logFile = new File(Logpath);
if(()){
long filesize =();
if(filesize>10*1020*1024){
//如果大于10M进行日志清理
();
writer= new OutputStreamWriter(new FileOutputStream(Logpath));
}else{
writer= new OutputStreamWriter(new FileOutputStream(Logpath,true));
}
}
else{
writer= new OutputStreamWriter(new FileOutputStream(Logpath));
}
}catch(Exception e){
Log.e(TAG, sage());
}
instance = new LogService();
}
return instance;
}
public synchronized void recordLog(String msg){
if(rdLog){
if(writer!=null){
try{
Date time = new Date();
}
((time)+" "+msg);
("n");
();
}catch(IOException e){
Log.e(TAG, sage());
}
}
}
}
13.发送和接收短信
接收短信
}
Bundle bundle = ras();
if (bundle != null) {
Object[] pdus = (Object[]) ("pdus");
SmsMessage[] msg = newSmsMessage[];
for (int i = 0; i < ; i++) {
}
content = msg[0].getMessageBody();
msg[i] = FromPdu((byte[]) pdus[i]);
private String strACT = "_RECEIVED";
if (ion().equals(strACT)) {
发送短信
}
privatevoidsendSMS(String phone, String message) {
// PendingIntent Pi = ivity(this, 0, new
// Intent(this,
// ), 0);
SmsManager sms = ault();
xtMessage(phone, null, message, null, null);
14.定时器
TimerTask task = newTimerTask() {
}
}
Timer timer = new Timer(true);
le(task,0,5000);
publicvoidrun() {
xt的常用操作
EditText input = new EditText(this);
//
只能输入数字
Listener(newDigitsKeyListener());
//
控制输入长度
ters(newInputFilter[]{Filter(10)});
/******************************************************/
//
监控字符变化
tChangedListener(new DSPTextWatcher());
publicclassDSPTextWatcherimplementsTextWatcher {
//
字符置顶
mater_use_vity();
getWindow().setSoftInputMode(
_INPUT_STATE_HIDDEN);
}
}
publicvoidonTextChanged(CharSequence arg0, int arg1, int arg2,
}
int arg3) {
Dosomethings();
// TODO Auto-generated method stub
}
publicvoidbeforeTextChanged(CharSequence arg0, int arg1, int
// TODO Auto-generated method stub
Dosomethings();
publicvoidafterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
Dosomethings();
arg2,int arg3) {
/******************************************************/
mater_use_ouchListener(new hListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
getWindow().setSoftInputMode(Params.
SOFT_INPUT_STATE_VISIBLE|_INPUT_ADJUST
_PAN);
return false;
}
});
//
获取光标位置插入字符等
EditText describe = new EditText (this);
String content=“test”;
//
获得当前光标位置
int current_position = ectionStart();
StringBuffer text = newStringBuffer(t().toString());
(current_position, content);
t(text);
//
得到添加插入后的光标位置
int pos = current_position + ();
ection(command_t(), pos);
16.时间的唯一标识符和UUID
Date timer = new Date();
Long id = e();
Long id2 = tTimeMillis();
String uuid = UUID().toString();
17.跨包启动ACTIVITY
ComponentName cn = newComponentName("",
"ra");
ponent(cn);
startActivityForResult(intent, 1);
18.Activity LaunchMode四种模式
android:launchMode="standard"
//
默认模式,点击
5
次打开五个
ACTIVITY
,重载
android:launchMode="singleTop"
//
只存在一个
ACTIVITY
如果在栈顶不重载,否则重载
android:launchMode="singleTask"
//
只存在一个
ACTIVITY
,不重载
android:launchMode="singleInstance"
//
至存在一个
ACTIVITY
,不重载
19.关闭全部程序
finalActivityManager am = (ActivityManager)
getSystemService(TY_SERVICE);
tPackage(getPackageName());
20.附件预览VIDEO,TXT,PIC
public class FilePreview extends Activity {
geBitmap(resizebm);
ale((float)currscale, (float)currscale);
Bitmap resizebm= Bitmap(bm, 0, 0, width, height,
if(currscale<0.2){
}
Matrix matrix = new Matrix();
kgroundResource(_out_up_un);
currscale =currscale*scale;
kgroundResource(_in_up);
}else{
private void small() {
int width = th();
int height = ght();
double scale = 0.8;
private Bitmap bm = null;
private ImageView iView;
private ScrollView sv ;
private DisplayMetrics dm;
private int offx=0;
private int offy=0;
private Button big,small;
private String attachType="";
private double currscale=1;
matrix, false);
}
private void big() {
int width = th();
int height = ght();
double scale = 1.25;
if(currscale>2){
;
}
public void onCreate(Bundle savedInstanceState){
long attachBeginTime=tTimeMillis();
te(savedInstanceState);
tance().recordLog("打开FilePreview!");
setTitle("附件预览");
sv= new ScrollView();
LinearLayout out=new LinearLayout();
entation(AL);
Intent intent = getIntent();
String path = ingExtra("preview_path");
int idx=f(".");
String type=ing(idx+1).toLowerCase();
//如果附件是图片
if(ns(type)){
attachType="图片";
//获取屏幕分辨率,根据屏幕分辨率创建界面
dm = new DisplayMetrics();
geBitmap(resizebm);
kgroundResource(_in_up_un);
}else{
currscale =currscale*scale;
kgroundResource(_out_up);
Matrix matrix = new Matrix();
ale((float)currscale, (float)currscale);
Bitmap resizebm = Bitmap(bm, 0, 0, width, height,
}
matrix, false);
getWindowManager().getDefaultDisplay().getMetrics(dm);
//根据不同的屏幕显示不同
if(Pixels==480&&ixels ==320){//480*320竖
}
if(Pixels==320&&ixels ==480){//480*320横
}
if(Pixels==800&&ixels ==480){//800*480竖
}
if(Pixels==480&&ixels ==800){//800*480横
}
//布局
AbsoluteLayout aLayout = new AbsoluteLayout(this);
offx=520;
offy=180;
offx=320;
offy=180;
offx=320;
offy=130;
offx=250;
offy=120;
屏幕
屏幕
屏幕
屏幕
kgroundColor(olor(oundC
olor));
Params
AbsLayoutParam = new
Params(
_PARENT,
AbsLayoutParam2 = new
_PARENT, 0, 50);
Params
Params(
_PARENT,
(ixels-offx), _PARENT,
(Pixels-offy));
Params AbsLayoutParamListBig = new
Params(
100, 45, (ixels-offx), 0);
Params AbsLayoutParamListSamll = new
100, 45, (ixels-offx+100), 0);
hscv=
new
Params(
HorizontalScrollView
HorizontalScrollView(this);
iView=new ImageView();
bm=File(path);
geBitmap(bm);
w(iView);
w(hscv);
big = new Button(this);
kgroundResource(_in_up);
lickListener(new kListener() {
@Override
public void onClick(View arg0) {
}
// TODO Auto-generated method stub
big();
});
w(big, AbsLayoutParamListBig);
small = new Button(this);
kgroundResource(_out_up);
lickListener(new kListener() {
@Override
public void onClick(View arg0) {
}
// TODO Auto-generated method stub
small();
});
w(small, AbsLayoutParamListSamll);
w(sv,AbsLayoutParam);
kgroundColor(olor(oundC
setContentView(aLayout);
olor));
}else
//如果附件是音频目前只支持3ga,mp3
if(ns(type)){
attachType="音频";
VideoView v=new VideoView();
//指定地址
eoPath(path);
//设置播放条
iaController(new MediaController(this));
//开始播放
();
w(v);
kgroundColor(olor(oundColor
setContentView(out);
));
}else
//如果附件是视频目前只支持3gp
if(ns(type)){
attachType="视频";
VideoView v=new VideoView();
//指定地址
eoPath(path);
//设置播放条
iaController(new MediaController(this));
//开始播放
();
w(v);
kgroundColor(olor(oundColor
//读取txt中内容
File f=new File(path);
}else
//如果附件是TXT格式文档
if(ns(type)){
attachType="TXT";
setContentView(out);
));
TextView v=new TextView();
byte[] buffer = null;
try {
}
String content = "";
try {
}
content = new String(buffer,"UTF-8");
// TODO Auto-generated catch block
tackTrace();
} catch (UnsupportedEncodingException e) {
InputStream in = new FileInputStream(f);
buffer = new byte[ble()];
(buffer);
// TODO Auto-generated catch block
tackTrace();
// TODO Auto-generated catch block
tackTrace();
} catch (FileNotFoundException e) {
} catch (IOException e) {
//设置内容
t(content);
w(v);
w(out);
kgroundColor(olor(oundColor
}
else{
setContentView(sv);
));
TextView v=new TextView();
t("附件类型无法解析!");
w(v);
kgroundColor(olor(oundColor
));
}
setContentView(out);
long attachEndTime=tTimeMillis();
tance().recordLog(attachType+"附件预览界面打开时
间为:"+(attachEndTime-attachBeginTime)+"微秒");
}
}
21.刷新ListView的用法
SimpleAdapter adapter;
HashMap Object>)m(selectedItem); if(b) ("img", ); ("img", ); else DataSetChanged(); 22.SharedPreferences的用法 SharedPreferences有三种访问模式:私有(MODE_PRIVATE),全局读 (MODE_WORLD_READABLE)和全局写(MODE_WORLD_WRITEABLE) //私有模式Public static int mode = MODE_PRIVATE; //全局读写Public static int mode _WORLD_READABLE+_WORLD_WRITEABLE; Public static final String PREFERENCE_NAME = “data”; SharedPreferencessp = getSharedPreferences(PREFERENCE_NAME, mode); //存储 editor = (); ing(“name”, "open"); (“Age”, 20); at(“Height”,1.81f); (); = //获取Stringname = ing(“name”, “default name”); //获取别的包下的SharedPreferences Public static final String preferences_package = “”; Public static final String preferences_name = “data”; Public Try { Contextc=PackageContext(preferences_package, static int mode = _WORLD_READABLE+_WORLD_WRITEABLE; T_IGNORE_SECURITY); }catch(){ } SharedPreferencessp =redPreferences(PREFERENCE_NAME, mode); 23.Spinner的简单用法 //一种方法从配置 ArrayAdapter> adapter1 = FromResource(this, , _spinner_item); //从ArrayList里面 ArrayList ("one"); adapter11 = newArrayAdapter _spinner_item, one); Spinners = new Spinner(this); pter(adapter11); 24.获取手机分辨率 DisplayMetricsdm = newDisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); 参数 X : Pixels 参数 Y : ixels 25.解析XML文件 privateList tance().recordLog("读取本地资源文件!"); List SAXReader reader = newSAXReader(); Document doc = null; try { } Element rootElement = tElement(); List elements = ts(); for (Object o : elements) { Element element = (Element) o; doc = (newBufferedReader(newInputStreamReader( newFileInputStream(XMLADDRESS), "GBK"))); } catch (Exception e) { tackTrace(); } } if (e().equals("row")) { } List values = ts(); SoftResourcePO softPO = newSoftResourcePO(); _id(ong(((Element) .getText())); (0)) tresource_no(((Element) softPO .setSoftresource_name(((Element) (2)) .getText()); (1)).getText()); softPO .setSoftresource_desc(((Element) (3)) .getText()); tresource_address_device(((Element) .getText()); .parseInt(((Element) (5)).getText())); (4)) tresource_orderno(Integer tresource_icon_chr(((Element) .getText()); (6)) tresource_icon_chr_offline(((Element) .get(7)).getText()); .parseLong(((Element) values tresource_fatherno(Long (8)).getText())); _offline(nt(((Element) .getText())); (9)) (softPO); returnsofts; 26.根据图片名称找到对应R里面的值 geResource(ld(pic_name).getInt(0) ); 27.监听网络连接 public class ConnectionChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent arg1) { // TODO Auto-generated method stub ConnectivityManager connetivityManager =(ConnectivityManager)temService(TIVITY_S ERVICE); } NetworkInfo activeNetInfo = //NetworkInfo mobNetInfo = if(activeNetInfo!=null){ iveNetworkInfo(); workInfo(_MOBILE); // 判断设置网络是否可用 ected(); } } 28.获取,内容 String arr[] = getResources().getStringArray(); 29.打开系统自带的相册并返回所选图像 Intent intent = new Intent(_GET_CONTENT); egory(RY_OPENABLE); e("image/*"); ra("return-data", "true"); startActivityForResult(intent, 0); if (requestCode == 0) { Bitmap cameraBitmap = (Bitmap)ras().get("data"); Uri uri = a(); String[] proj = {}; Cursor cursor = managedQuery(uri, proj, null, null,null); int column_index First(); =umnIndexOrThrow(); } path = ing(column_index); 30.根据颜色值着色 kgroundColor(olor(#ffffff)); 31. Makejar的2种方法 1) JAVA代码加校验实现 ///jar cvf import .*; import order; import .*; import Event; import Listener; import .*; import DateFormat; import ist; import ar; import p; import ; import .*; public class MakeJAR extends JFrame { /** * 提供两个方法, R(),支持界面选择输入路径和输出路径; R(String dirfile, String * targetfile),dirfile为打包目录的路径;targetfile为输出路径。 */ private static final long serialVersionUID = 1L; private static JarOutputStream jos; private static byte buf[] = new byte[1024]; private static int len; private static int totalFileCount; private static int doneFileCount; private JTextField jarDirField; private JTextField jarTargetField; private static JProgressBar progressBar; private static ArrayList private static Map private static HashMap public static void main(String[] args) { new MakeJAR(); } // 传两个参数:dirfile为要打包的路径;targetfile为输出路径。 public MakeJAR(String dirfile, String targetfile) { super("JAR Maker"); performed(dirfile, targetfile); } // 从界面选择输入路径和输入路径 public MakeJAR() { super("JAR Maker"); valMap = new ValTypes().setTypes(); jarDirField = new JTextField(20); jarTargetField = new JTextField(20); final JFileChooser jcdir = new JFileChooser(); final JFileChooser jctar = new JFileChooser(); JButton dir = new JButton(); t("选择目录"); ionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { eSelectionMode(1); enDialog(null); t(ectedFile().getPath()); } }); JButton tar = new JButton(); t("保存地址"); ionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { eSelectionMode(1); eptAllFileFilterUsed(true); veDialog(null); Calendar c = tance(); String time = new SimpleDateFormat("yyyyMMddHHmmss").format(c .getTime()); t(ectedFile().getPath() + "" + time + ".war"); } }); JPanel mainPanel = new JPanel(); der(new EmptyBorder(3, 3, 3, 3)); out(new BoxLayout(mainPanel, 1)); JPanel dirPanel = new JPanel(); JPanel targetPanel = new JPanel(); der(TitledBorder("输入操作的项目路径")); targetPanel .setBorder(TitledBorder("输入要打成的jar包的名称")); (jarDirField); (dir); (jarTargetField); (tar); JPanel panel3 = new JPanel(); der(new EmptyBorder(5, 5, 5, 5)); out(new BorderLayout()); JButton startButton = new JButton("打JAR包"); ionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String wfStr1 = new String(t()); String wfStr2 = new String(t()); performed(wfStr1, wfStr2); } }); (startButton, "East"); (dirPanel); (targetPanel); (panel3); getContentPane().add(mainPanel); pack(); } Dimension screen = aultToolkit().getScreenSize(); Dimension size = getSize(); setLocation(( - ) / 2, ( - ) / 2); aultCloseOperation(_ON_CLOSE); setVisible(true); public static void makeZip(File directory, File zipFile) throws IOException, FileNotFoundException { jos = new JarOutputStream(new FileOutputStream(zipFile)); String fileNames[] = (); if (fileNames != null) { for (int i = 0; i < ; i++) recurseFiles(new File(directory, fileNames[i]), ""); } (); } private static void recurseFiles(File file, String pathName) throws IOException, FileNotFoundException { if (ctory()) { pathName = pathName + e() + "/"; tEntry(new JarEntry(pathName)); String fileNames[] = (); if (fileNames != null) { for (int i = 0; i < ; i++) recurseFiles(new File(file, fileNames[i]), pathName); } } else { String filename = e(); String versionTemp = (filename); if (versionTemp != null) { String version = getJarVersion(h()); int temp = compareVersion(versionTemp, version); String result = temp == 0 ? "通过" : "未通过"; n(filename + "的校验结果为:" + result); if (temp == -1) { (filename); } } JarEntry jarEntry = new JarEntry(pathName + filename); n(pathName + " " + filename); } } FileInputStream fin = new FileInputStream(file); BufferedInputStream in = new BufferedInputStream(fin); tEntry(jarEntry); while ((len = (buf)) >= 0) (buf, 0, len); (); ntry(); doneFileCount++; ue(doneFileCount); public void performed(String dirfile, String targetfile) { String wfStr1 = dirfile; String wfStr2 = targetfile; final File jarDir = new File(wfStr1); // int temp = ().lastIndexOf("."); // if (temp != -1) { // wfStr2 = ing(0, temp); // } final File jarFile = new File(wfStr2); if (!(new File(jarDir, "WEB-INF")).exists()) { String msg = "无效的路径,请重新选择!"; ssageDialog(, msg, "Error!", 0); } else if (().equals("")) { String msg = "名称无效,请重新输入!"; ssageDialog(, msg, "Error", 0); } else { countFiles(jarDir); progressBar = new JProgressBar(0, totalFileCount); ue(0); ingPainted(true); setVisible(false); getContentPane().removeAll(); JPanel panel = new JPanel(); (progressBar); getContentPane().add(panel); pack(); setVisible(true); Thread t = new Thread() { public void run() { try { makeZip(jarDir, jarFile); if (() < 1) { String msg = "jar包已保存到: " + onicalPath(); ssageDialog(, msg, "打包成功", -1); } else { String meString = ""; for (int i = 0; i < (); i++) { } meString = meString + (i) + ";"; String msg = "下列Jar包的版本低可能导致程序不能正常运 行:" + ing(0, () - 1); ssageDialog(, msg, "校验失败", -1); // (); } } catch (Exception e) { n(e); } (0); } }; (); } } // private void performed(String wfStr1, String wfStr2) throws IOException { // // time().exec("jar -cvf "+wfStr1+" "+wfStr2+"/*"); // } // 比较版本号,-1表示版本低或者不匹配,0表示版本匹配 private static int compareVersion(String version1, String version2) { if (version1 != null && version2 != null) { String[] arr1 = ().split("."); String[] arr2 = ().split("."); } int max = (, ); for (int i = 0, i1 = 0; i <= max; i++) { } if (i == ) { return i == ? 0 : -1; } else if (i == ) { return 0; } else { } i1 = arr2[i].compareTo(arr1[i]); if (i1 > 0) { return 0; } else if (i1 < 0) { } return -1; } return -1; private static String getJarVersion(String path) { try { String filename = "META-INF/"; JarFile jarFile = new JarFile(path); // Enumeration enms = s(); // while (eElements()) { // JarEntry entry = (JarEntry) ement(); // String name = e(); // if ((filename)) // break; // } JarEntry entry = Entry(filename); InputStream input = utStream(entry); } } InputStreamReader isr = new InputStreamReader(input); BufferedReader reader = new BufferedReader(isr); String line; while ((line = ne()) != null) { parseLine(line); } (); String value = ("Implementation-Version"); n("jar包的版本型号为:" + value); return value; } catch (IOException e) { // TODO Auto-generated catch block tackTrace(); return null; } // 解析Minifest的版本信息 private static void parseLine(String line) { // TODO Auto-generated method stub if (s(".*:.*")) { int i = f(":"); String name = ing(0, i); String value = ing(i + 1); name = (); value = (); (name, value); } } private void countFiles(File file) { if (ctory()) { String fileNames[] = (); if (fileNames != null) { for (int i = 0; i < ; i++) countFiles(new File(file, fileNames[i])); } } else { totalFileCount++; } } 2) 命令代码实现 time().exec("jar -cvf "+dirpath+" "+tarpath +"/*"); 32. create tablespace create tablespace officedata datafile 'e:' size 200m default storage (initial 40k next 40k pctincrease 0 minextents 1 maxextents unlimited) 33. 获取URL信息 import tputStream; import tream; import Stream; import ; publicclass GetUrl { publicstaticvoid main(String []args){ InputStream in = null; OutputStream out = null; try { if((!=1)&&(!=2))thrownew URL url = new URL(args[0]); in = ream(); if(==2){ } else out= ; out = new FileOutputStream(args[1]); IllegalArgumentException("Wrong number of args"); byte[] buffer = newbyte[4096]; int bytes_read; while ((bytes_read=(buffer))!=-1 ){ } } } } (buffer,0,bytes_read); } catch (Exception e) { // TODO: handle exception try { } (); (); // TODO: handle exception }finally{ } catch (Exception e2) { 34. 图片放大缩小适中屏幕 dm = newDisplayMetrics(); if(currscale>2 or <0.2){ Matrix matrix = newMatrix(); ale((float)currscale, (float)currscale); Bitmap resizebm = Bitmap(bm, 0, 0, width, height, kgroundResource(_in_up_un); bled(false); currscale =currscale*scale; kgroundResource(_out_up); bled(true); getWindowManager().getDefaultDisplay().getMetrics(dm); int width = th(); int height = ght(); double scale = 1.25 or 0.8; privatevoidbig or small() { private Bitmap bm = null; private double currscale=1; private ScrollView sv ; private DisplayMetrics dm; }else{ } matrix, false); bmHeight = ght(); bmWidth = th(); AbsLayoutParamPicture = new Params( _PARENT, _PARENT, (ixels - bmWidth)>0?(ixels - bmWidth)/2:0, (Pixels-offy-50-bmHeight)>0?50+(Pixels-offy-50- } View(sv); geBitmap(resizebm); w(sv,AbsLayoutParamPicture); bmHeight)/2:50); 35. 文本文件翻页 //第一次显示 File f=new File(path); fileOutStream = newRandomAccessFile( f, "r"); (perpageWord*position); (buffer); String content = new String(buffer,"UTF-8"); //翻页 privatevoidshowText(int add){ if(add==-1){ //-1:前一页 if(position>0){ byte[] buffer = newbyte[perpageWord]; position--; try { (perpageWord*position); (buffer); Stringcontent = newString(buffer,"UTF-8"); t(content); // TODO Auto-generated catch block } catch (IOException e) { } } tackTrace(); if(perpageWord*(position+1)>=filetotleLength){ bled(false); bled(true); }else{ } if(position==0){ bled(false); bled(true); } if(add==1){ //后一页 if(perpageWord*(position+1)<=filetotleLength){ } byte[] buffer = newbyte[perpageWord]; position++; try { } (perpageWord*position); (buffer); String content = newString(buffer,"UTF-8"); t(content); // TODO Auto-generated catch block tackTrace(); return; }else{ } } catch (IOException e) { if(perpageWord*(position+1)>=filetotleLength){ bled(false); bled(true); }else{ } if(position==0){ bled(false); bled(true); } return; }else{ } } 36. 根据图片名称反射R的值 ld(picName).getInt(0); Class c = e(address); 自定义jsp标签并在WebPageEditor中使用 by:changxw 前期准备 JSP自定义标签:在自定义标签的起始和结束标签之间的部分为标签体(Body)。 标签处理程序类:定义标签的行为,并在JSP引擎遇到自定义标签时调用执行。 标签库描述符(TLD)文件:描述标签库的XML文档,向JSP引擎提供有关自定义标签 的标签处理程序的信息。tag标签相关属性:实现简单标签处理程序标签处理程序是一个在 运行时调用的Java类,它包含在 JSP文件中使用的自定义标签的实现代码.标签处理程序必须 实现或扩展包中的类和接口.含有允许标签处理程序类与JSP 容器通信的接口和类。自定义标签已经早有接触了(Struts中使用了很多自定义标签,如html、 bean等) 使用这种技术的优点:取代了JSP中的Java程序,并且可以重复使用,方便不熟 悉Java编程的网页设计人员。 自定义标签 步骤1: 在eclipse3.4及以上javaEE版本中, 创建任意java工程,导入包, 到工程。 步骤2: 在根目录创建包结构如下: 并在tlds包下创建相应的tld文件。 例如: //标签库根元素 //uri标签库唯一标识 //标签定义 //标签名字 //标签处理类全限定名 //标签体是否为空 //标签属性 //属性名 //当前属性是否必须填写,默认为false // 步骤3:在src包下编写对应标签的处理类。 标签处理类需要继承 SimpleTagSupport类,重写doTag()方法。 利用JspWriter写如标签的处理信息。 例如: JspWriterout=getJspContext().getOut();” (“hello world”); 属性处理方法: 假如现在要自定义一个 button标签,,我们可以直接写: (“”);即可 如果属性较少的话,我们可以在处理类中直接生成他们的get和set方法然后加入到字符串 中。 但是如果标签的属性有很多怎么办?我们不可能都以硬编码的方式写,并且有些标签的属性并不 一定会用到。 我这里是这样处理的: 定义一个Attributes类,将一些通用属性封装在本类中,用Map存储这些属性。 publicclassAttribute{ /** * 使用两个Map分别存储属性的名称和属性值,以相同的key值控制对应关系, * * */ 因为此处依赖关系总是标签依赖Attribute类,用构造注入,以减少代码之间的耦合。 Attribute类中定义的是大部分通用的属性 *@authorchangxw privatestaticStringcont; publicMap staticpublicMap static{ } publicAttribute(Stringtype, Stringvalue,Stringonclick,Stringid,Stringstyle,Stringtitle,Stringaccept,Stringaccesskey, Stringalign,Stringalt){ } /** * *@paramkey *@return */ publicStringgetAttribute(Stringkey){ } } cont=(key); returncont; (1,type); (2,value); (3,onclick); (4,id); (5,style); (6,title); (7,accept); (8,accesskey); (9,align); (10,alt); (1,"type"); (2,"value"); (3,"onclick"); (4,"id"); (5,"style"); (6,"title"); (7,"accept"); (8,"accesskey"); (9,"align"); (10,"alt"); 这样在用到的时候可以在相应的标签处理类中传入相应的属性值即可。 下面在标签处理类中使用它: 处理类中仅需 继承 SimpleTagSupport类,重写doTag()方法,并封装所有属性,提供他们的 get和set方法。 public class Date extends SimpleTagSupport { Attribute att; att=newAttribute(getType(),getValue(),getOnclick(),getId(),getStyle(),getTitle(),getAccept(),getA } ccesskey(),getAlign(),getAlt()); privatebooleantimeOnly; @Override publicvoiddoTag()throwsJspException,IOException{ //通过Attribute构造传入获取的属性值 JspWriterout=getJspContext().getOut(); StringBuffersb=newStringBuffer(); (""); if((i)!=null){ } ("t"); ((i)+"=""+(i)+"""); n(ng()); (ng()); } 如果很多标签都需要用到这些通用的属性,那么这样做是比较好的。 其他的标签处理父接口: 例如:TagSupport 1. import ption; 2. import eption; 3. import Exception; 4. import port; 5. /** 6. * TagSupport与BodyTagSupport的区别: 7. * 主要看标签处理类是否要读取标签体的内容和改变标签体返回的内容,如果不需要就用TagSuppo rt,否则就用BodyTagSupport 8. * 用TagSupport实现的标签,都可以用BodyTagSupport来实现,因为BodyTagSupport继承了TagS upport 9. */ 10. public class HelloWorldTag extends TagSupport { 11. private static final long serialVersionUID = 3174234L; 12. @Override 13. public int doStartTag() throws JspException {//这个方法不用所以直接返回值 14. return EVAL_BODY_INCLUDE; 15. } 16. @Override 17. public int doEndTag() throws JspException {//重点在这个方法上 18. try { 19. ().write("Hello World!");//标签的返回值 20. } catch (IOException ex) { 21. throw new JspTagException("错误"); 22. } 23. return EVAL_PAGE; 24. } 25. } doStartTag()方法是遇到标签开始时会呼叫的方法,其合法的返回值是EVAL_BODY_INCLUDE与 SKIP_BODY,前者表示将显示标签间的文字,后者表示不显示标签间的文字。 doEndTag()方法是在遇到标签结束时呼叫的方法,其合法的返回值是EVAL_PAGE与SKIP_PAGE,前者表 示处理完标签后继续执行以下的JSP网页,后者是表示不处理接下来的JSP网页。 doAfterBody(),这个方法是在显示完标签间文字之后呼叫的,其返回值有EVAL_BODY_AGAIN与 SKIP_BODY,前者会再显示一次标签间的文字,后者则继续执行标签处理的下一步。 EVAL_BODY_INCLUDE:把Body读入存在的输出流中,doStartTag()函数可用。 EVAL_PAGE:继续处理页面,doEndTag()函数可用。 SKIP_BODY:忽略对Body的处理,doStartTag()和doAfterBody()函数可用。 SKIP_PAGE:忽略对余下页面的处理,doEndTag()函数可用。 EVAL_BODY_BUFFERED:申请缓冲区,由setBodyContent()函数得到的BodyContent对象来处理tag的 body,如果类实现了BodyTag,那么doStartTag()可用,否则非法。 EVAL_BODY_AGAIN:请求继续处理body,返回自doAfterBody(),这个返回值在你制作循环tag的时候 是很有用的。 预定的处理顺序是:doStartTag()返回SKIP_BODY,doAfterBodyTag()返回SKIP_BODY,doEndTag()返回 EVAL_PAGE。如果继承了TagSupport之后,如果没有改写任何的方法,标签处理的执行顺序是:doStartTag() ->不显示文字 ->doEndTag()->执行接下来的网页 。如果改写了doStartTag(),则必须指定返回值,如果指定 了EVAL_BODY_INCLUDE,则执行顺序是:doStartTag()->显示文字->doAfterBodyTag()->doEndTag()->执行 下面的网页 。 动态属性: 当要传入的属性个数和属性名都不确定时,使用动态属性即可解决。 要求:1.标签处理类继承SimpleTagSupport并实现DynamicAttributes接口。 2.配置标签时通过 步骤4:将这个java工程打成jar包暂存后面使用。 这个jar包中仅需要如下内容即可: -INF文件夹,下面有一个tlds的文件夹存放tld文件 2.若干标签处理类,可以把他们放置到一个文件夹中,但一定要与tld中 路径 相同。 提示:如果标签带有属性,一定要在标签处理类中为每一个属性生成其对应的 get和set方法!因为WPE默认机制就是去通过set方法给属性赋值的。 (上面的标签处理类中所说到的很多属性的问题,这里还要再说一下:上面的方式其实 叫做javaBeans模式我们定义的每一个标签处理类就像当与这个标签的实体,在其中定义标 签属性,并为其生成相应的get和set方法。做法不是不可以,只是对于构造器来说负担太 重,并且代码的可阅读性也不高,如果增加一个标签,由程序员手动输入参数,参数位置颠 倒或者不符合实际时编译器不会报错,但是运行的时候肯定会出现错误,那么要避免这样的 问题,这里提供一些其他的方法。 第一种是将所有通用属性抽取出来,在一个类中定义例如上面的Attribute,并生成他们 的getter和setter,在每个标签中仅定义他的专属属性,这样做的好处是代码的重用比较高, 而且我们还定义了一个类似不可更改的类,不可更改的类是安全的;但是,如果大多标签的 专有属性也很多(大于5个),特别是如果通用属性和专有属性的个数差不多的极端状况,更 甚至是通用属性比专有属性还要少的情况下我们刚才工作就没有优势了,这种方法便会显得 毫无意义! 第二种方法是我个人比较推荐使用的,叫做构建器(builder)模式。主类构造方法不是用 来直接生成实例,而是去调用构建器,由构建器实例调用其内部各个属性的set方法,以此 为主类的参数赋值,builder的setter方法返回builder本身以便可以把调用连接起来,最后 客户端调用无参数的build方法来生成原本标签实体的不可变的对象。这样做的好处是我们 不必担心因为有过多的属性,在传递参数的时候出现错误,因为我们是以属性名字命名的 set方法来向属性传递参数的。下面给出一个简单的例子: packageformBasic; /** * * @authorchangxw * */ publicclassBuilderTestTag{ privatefinalStringname; privatefinalStringid; privatefinalStringtype; privatefinalStringencode; privatefinalStringcharge; privatefinalStringvalidate; publicstaticclassBuilder{ } privateBuilderTestTag(Builderbuilder){ =; =; =; =; =; privatefinalStringid; privatefinalStringencode; privateStringtype=""; privateStringname=""; privateStringcharge=""; privateStringvalidate=""; publicBuilder(Stringid,Stringencode){ } publicBuildertype(Stringtype){ } publicBuildername(Stringname){ } publicBuildercharge(Stringcharge){ } publicBuildervalidate(Stringvalidate){ } publicBuilderTestbuild(){ } returnnewBuilderTestTag(this); te=validate; returnthis; =charge; returnthis; =name; returnthis; =type; returnthis; // TODO Auto-generated constructor stub =id; =encode; } } te=te; 客户端: publicstaticvoidmain(String[]args){ } Stringcharge=; Stringname=; Stringid=; Stringtype=; Stringencode=; Stringvalidate=te; n(charge+","+name+","+id+","+type+","+encode+","+validate); BuilderTesttag=newBuilderTest. Builder("id","encode").charge("charge").name("name").type("type").validate("validate").build(); 当然,这里只是一种想法,并没有在标签处理类中真正实现,如果想要应用可能还需要进行 改进!因为我们知道,一个标签的属性一定是要提供相应的get和set方法) 使用标签 步骤1: 创建一个插件工程,创建metadata包,在其中创建对应你的tld文件的xml描述文件, 名字最好一样。 例如: xmlns:xsi="/2001/XMLSchema-instance" xmlns:ecore="/emf/2002/Ecore" xmlns:md="ta/" xmlns:mdt="ta/" xmlns:pi="signer/" id="box" type="tagFile"> 义多个 标签,根据id在下面的 定义 entity详细 //palette的设置名 //item表示一个标签,可以定 //标签库图片所在,在运行时即加载 信息 信息 中的一 致 //鼠标划过相应标签显示的描述 //type是必须写成tag,id一定要与 上面的 //鼠标划过标签库时显示的描述 //palette中标签库的显示名称 //palette中标签的显示名称 //标签的小图标 //标签的大图标 步骤2: 在文件中注册刚才创建的标签库。 例如: //uri保持一致 location="/metadata/" uri="box"> 步骤3: run as EclipseApplication来测试你刚才创建的标签,在打开的eclipse镜像中创建一个 web工程,将上面创建好的java工程的jar包复制到web工程中WebContent下WEB-INF下 的lib目录中,用webPageEditor打开一个jsp文件,palette中即会显示你所创建的标签库。 这里需要注意:如果WebPageEditor运行正常,当你从自定义的标签库中拖拽一个标签 到编辑器中,会自动生成一段taglib声明到编辑器,如果此时没有自动生成,请手动敲入taglib 的jsp声明,如: <%@ taglib prefix=”test” uri=”test”%> uri 与tld文件定义的需要一致,prefix会是将要显示到自定义标签前部的信息: 这样,自定义的标签也就成功使用了,在服务器上跑一下看看效果吧。 常见问题: 1.部分情况下运行run as eclipseApplication 时可能会因为分配给系统的内存过低而报错,在 RunConfigurations里面进行修改: 一般在Arguments的程序和VM参数中里增加这样两行:-XX:MaxPermSize=xxxM -XX:PermSize=xxxM即可。为了启动eclipse性能考虑,一般最大最小值设成一样的即可。 余下问题: 1. Eclipse属性页,不支持自定义标签的下拉选择或者弹框选择,需要自己重新去实现, 并熟悉eclipse插件开发。工作量较大,参考普元的EOS中的实现。 2. 封装好的标签需要引用脚本的(即,在将一段脚本封装到标签里,该标签才能显示效 果的),如果多次拖拽该标签,则会有多段脚本,那么此时将显示不正常!尝试定义 一个“是否引用脚本”的属性,当检测到jsp文件中的该标签大于1时,则余下拖拽 的标签在处理类中将根据判断不打印脚本段代码。并且注意,标签的“id”属性不可 以重复,否则无法显示。 3. 标签帮助,参考eclipse插件开发教程,为每一个标签编写详细的帮助信息。 加油!兄弟!


发布评论