位置: 编程技术 - 正文

android 常用代码(安卓通用代码)

编辑:rootadmin
1.FILE工具

推荐整理分享android 常用代码(安卓通用代码),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:android代码结构,android程序代码,安卓常用代码,android代码是什么语言,android 代码规范,android 代码规范,android 代码规范,android代码大全,内容如对您有帮助,希望把文章链接给更多的朋友!

// 创建文件,参数包括路径(不能为空),文件名称,内容

public static void makefile(String path,String filename,String content) {

File dir =newFile(path);

if (!dir.exists()) {

dir.mkdir();

}

// dir.mkdir();

File newFile =null;

if(path!=null){

newFile = new File(dir.getAbsolutePath()&#;"/"&#;filename);

FileOutputStream fos =null;

try {

newFile.createNewFile();

if (newFile.exists() && newFile.canWrite()) {

fos = newFileOutputStream(newFile);

fos.write(content.getBytes());

}

} catch (IOException e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

} finally {

if (fos !=null) {

try {

fos.flush();

fos.close();

} catch (IOException e) {

// TODO: handleexception

}

}

}

}

}

2.下载图片工具

public class DownloadPicUtil{

/**

*

* @paramurl

* @paramfilename

* @return0没有图片;return1成功;return2IO 异常;

*/

public static int DownLoadBitmap(String url,Stringfilename) {

// TODO Auto-generatedmethod stub

InputStream inputStream=null;

DefaultHttpClient client =newDefaultHttpClient();

try {

HttpGet request=newHttpGet(url);

HttpResponse response=client.execute(request);

int statusCode = response.getStatusLine().getStatusCode();

if(statusCode!=HttpStatus.SC_OK){

return 0;

}else{

HttpEntity entity =response.getEntity();

inputStream = entity.getContent();

Bitmap bitmap =BitmapFactory.decodeStream(inputStream);

//图片可以在这个时候存储到sdcard上

saveBitmap(bitmap,filename);

return 1;

}

}catch (Exception e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

return 2;

}finally{

if(inputStream!=null){

try {

inputStream.close();

} catch (IOException e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

}

}

}

}

public static void saveBitmap(Bitmap bitName,String filename) {

String filepath ="/sdcard/baomi/";

File f =newFile(filepath&#;filename);

FileOutputStream fout =null;

try{

f.createNewFile();

fout = new FileOutputStream(f);

bitName.compress(Bitmap.CompressFormat.PNG,,fout);

fout.flush();

fout.close();

}catch(Exception e){

e.printStackTrace();

}

}

}

3.http请求工具

public class HttpUtil{

public static String SESSION_ID=null;

public static HttpResponse getHttpResponse(HttpGet request)throws ClientProtocolException,IOException{

BasicHttpParams httpParams =newBasicHttpParams();

LogService.getInstance().recordLog("进入getHttpResponse");

HttpConnectionParams.setConnectionTimeout(httpParams,

SysConfig.nConnectionTimeout);

LogService.getInstance().recordLog("超时时间为:"&#;SysConfig.nConnectionTimeout);

HttpConnectionParams.setSoTimeout(httpParams,SysConfig.nSoTimeout);

LogService.getInstance().recordLog("Socket超时时间为:"&#;SysConfig.nSoTimeout);

DefaultHttpClient httpClient =newDefaultHttpClient(httpParams);

LogService.getInstance().recordLog("获得响应客户端");

HttpResponse response=httpClient.execute(request);

LogService.getInstance().recordLog("获得结果");

httpClient.getConnectionManager().shutdown();

LogService.getInstance().recordLog("关闭连接");

return response;

}

public static HttpResponse getHttpResponse(HttpPost request)throws ClientProtocolException,IOException{

BasicHttpParams httpParams =newBasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParams,

SysConfig.nConnectionTimeout);

HttpConnectionParams.setSoTimeout(httpParams,SysConfig.nSoTimeout);

DefaultHttpClient httpClient =newDefaultHttpClient(httpParams);

HttpResponse response=httpClient.execute(request);

httpClient.getConnectionManager().shutdown();

return response;

}

//通过url发送post请求,并返回结果

public static String queryStringForPost(String url){

LogService.getInstance().recordLog("发送POST请求");

HttpPost request =newHttpPost(url);

String result=null;

try {

HttpResponse response=HttpUtil.getHttpResponse(request);

LogService.getInstance().recordLog("POST返回状态为"&#;response.getStatusLine().getStatusCode());

if(response.getStatusLine().getStatusCode()==){

result=EntityUtils.toString(response.getEntity());

return result;

}

} catch (Exception e) {

LogService.getInstance().recordLog("POST异常:"&#;e.getMessage());

e.printStackTrace();

result="网络异常";

return result;

}

return null;

}

//通过url发送GET请求并返回结果

public static String queryStringForGet(String url){

LogService.getInstance().recordLog("发送GET请求");

String result=null;

try {

ResponseHandler<String> responseHandler =newBasicResponseHandler();

HttpClient httpclient =newDefaultHttpClient();

LogService.getInstance().recordLog("提交的地址为:"&#;url);

HttpGet httpget =newHttpGet(url);

result =httpclient.execute(httpget, responseHandler);

LogService.getInstance().recordLog("GET返回状态为"&#;result);

return result;

} catch (Exception e) {

LogService.getInstance().recordLog("GET异常:"&#;e.getMessage());

e.printStackTrace();

result="网络异常";

return result;

}

}

//通过HttpPost发送POST请求,并返回结果

public static String queryStringForPost(HttpPost request){

String result=null;

try {

HttpResponse response=HttpUtil.getHttpResponse(request);

if(response.getStatusLine().getStatusCode()==){

result=EntityUtils.toString(response.getEntity());

return result;

}

} catch (Exception e) {

e.printStackTrace();

result="网络异常";

return result;

}

return null;

}

}

4.JSon工具

public class JSonUtil {

public static String string2json(String s){

StringBuildersb = new StringBuilder(s.length()&#;);

sb.append('"');

for(int i=0;i<s.length();i&#;&#;){

charc =s.charAt(i);

switch(c){

case'"':

sb.append("\"");

break;

case'\':

sb.append("\\");

break;

case'/':

sb.append("\/");

break;

case'b':

sb.append("\b");

break;

case'f':

sb.append("\f");

break;

case'n':

sb.append("\n");

break;

case'r':

sb.append("\r");

break;

case't':

sb.append("\t");

break;

default:

sb.append(c);

}

}

sb.append('"');

returnsb.toString();

}

public static String number2json(Number number){

returnnumber.toString();

}

public static String boolean2json(Boolean bool){

returnbool.toString();

}

public static String map2json(Map map){

if(map.isEmpty()){

return"[]";

}

StringBuildersb = new StringBuilder(map.size()<<4);

sb.append("{");

Set<String>keys = map.keySet();

for(Stringkey :keys){

Objectvalue = map.get(key);

sb.append('"');

sb.append(key);

sb.append('"');

sb.append(":");

sb.append(tojson(value));

sb.append(',');

}

sb.setCharAt(sb.length()-1,'}');

returnsb.toString();

}

public static String array2json(Object[] array){

if(array.length==0){

return"[]";

}

StringBuildersb = new StringBuilder(array.length<<4);

sb.append("[");

for(Objecto:array){

sb.append(tojson(o));

sb.append(',');

}

sb.setCharAt(sb.length()-1,']');

returnsb.toString();

}

public static String tojson(Objecto){

if(o==null)

return"null";

if(oinstanceof String)

returnstring2json((String)o);

if(oinstanceof Boolean)

returnboolean2json((Boolean)o);

if(oinstanceof Number)

returnnumber2json((Number)o);

if(oinstanceof Map)

returnmap2json((Map)o);

if(oinstanceof Object[])

returnarray2json((Object[])o);

thrownew RuntimeException("Unsupported type :"&#;o.getClass().getName());

}

/*Servlet输出json

response.setContentType("application/json;charset=UTF-8");

response.setCharacterEncoding("UTF-8");

PrintWriter pw =response.getWriter();

pw.write(JSonUtil.tojson(obj));

pw.flush();

*/

}

5.Stirng encode 转ucs2码 双字节

public class StringUtil {

public static String StringToHex(String input) {

String result ="";

if (input !=null) {

byte[] bytes =null;

try {

bytes = input.getBytes("UTF-BE");

} catch (Exception e) {

// TODO Auto-generatedcatch block

return null;

}

StringBuffer reValue =newStringBuffer();

StringBuffer tem =newStringBuffer();

for (int i = 0; i < bytes.length; i&#;&#;) {

tem.delete(0, tem.length());

tem.append(Integer.toHexString(bytes[i] & 0xFF));

if (tem.length() == 1) {

tem.insert(0,'0');

}

reValue.append(tem);

}

result = reValue.toString().toUpperCase();

return result;

} else {

return"";

}

}

public static String HexToUTFBE(String input) {

String result ="";

if (input !=null) {

byte[] bytes1 =newbyte[input.length() / 2];

for (int i = 0; i < input.length(); i &#;= 2) {

bytes1[i / 2] = (byte) (Integer.parseInt(input.substring(i,

i &#; 2), ));

}

try {

result = newString(bytes1,"UTF-BE");

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

return null;

}

return result;

} else {

return "";

}

}

}

6.Notification实例

NotificationManager notificationManager=(NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);

//定义一个Notification

Notification m_notification =newNotification();

//设置Notification的各种属性

//设置通知在状态栏的图标

m_notification.icon = R.drawable.icon;

//当我们点击通知时显示的内容

m_notification.tickerText = "BUTTON1通知内容";

//通知时发出的默认声音

m_notification.defaults = Notification.DEFAULT_SOUND;

//设置通知显示的参数

Intent intent =newIntent();

PendingIntent m_pendingIntent =PendingIntent.getActivity(testNotification.this,0,intent,0);

m_notification.setLatestEventInfo(testNotification.this,"BUTTON","BUTTON1通知内容",m_pendingIntent);

//开始执行通知

i&#;&#;;

notificationManager.notify(i,m_notification);

7.POSTURL Theard

public class PostThread extends Thread {

private static Context context;

private PostURL[] posturls;

private HttpResponse httpResponse;

private DefaultHttpClient httpClient;

private HttpPost httpRequest;

private static BasicHttpParams httpParams;

private static PostURLAdapter adapter;

private String[] sparams ;

private String[] sfiles;

private List<NameValuePair> params ;

public PostThread(Context context) {

super();

this.context = context;

adapter = new PostURLAdapter(context);

adapter.open();

httpParams = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParams,

SysConfig.nConnectionTimeout);

HttpConnectionParams.setSoTimeout(httpParams,SysConfig.nSoTimeout);

httpClient = newDefaultHttpClient(httpParams);

}

public static int PostWithFile(String posturl,Map<String,String> postparam,Map<String,String> postfile,String type){

String end ="rn";

String prefix ="--";

String boundary ="*****";

try {

URL url =newURL(posturl);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

StringBuilder sb =newStringBuilder();

FileInputStream fStream=null;

/* 允许Input、Output,不使用Cache */

con.setConnectTimeout(SysConfig.nConnectionTimeout);

con.setReadTimeout(SysConfig.readFileTimeout);

con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

/* 设置传送的method=POST */

con.setRequestMethod("POST");

/*setRequestProperty */

con.setRequestProperty("Connection","keep-alive");

con.setRequestProperty("Charset","UTF-8");

con.setRequestProperty("Content-Type",

"multipart/form-data;boundary=" &#; boundary);

// // 拼接参数(不包括文件)

List<NameValuePair> localparams =newArrayList<NameValuePair>();

for (Map.Entry<String,String> entry : postparam.entrySet()) {

sb.append(prefix);

sb.append(boundary);

sb.append(end);

sb.append("Content-Disposition:form-data;name="" &#; entry.getKey()

&#; """&#;end&#;"Content-Type:text/plain;Charset=UTF-8"&#;end );

if(type.equals("0")){

sb.append("Content-Transfer-Encoding:8bit"&#;end&#;end&#; entry.getValue() &#; end);

}else{

sb.append("Content-Transfer-Encoding:8bit"&#;end&#;end&#; ((entry.getValue()==null||entry.getValue().equals(""))?StringUtil.StringToHex(""):StringUtil.StringToHex(entry.getValue()))&#; end);

}

}

// /* 设置DataOutputStream*/

DataOutputStream ds =newDataOutputStream(con.getOutputStream());

Stringt=sb.toString();

ds.write(sb.toString().getBytes());

//发送文件

for (Map.Entry<String,String> entry : postfile.entrySet()) {

sb = newStringBuilder();

sb.append(prefix);

sb.append(boundary);

sb.append(end);

sb.append("Content-Disposition:form-data;name=""

&#; entry.getKey()

&#; "";filename=""

&#; entry.getValue().substring(

entry.getValue().lastIndexOf('/') &#; 1) &#;"""

&#; end);

sb.append("Content-Type:application/octet-stream;Charset=UTF-8"

&#; end &#; end);

ds.write(sb.toString().getBytes());

/* 取得文件的FileInputStream */

fStream = newFileInputStream(entry.getValue());

/* 设置每次写入bytes */

int bufferSize = ;

byte[] buffer =newbyte[bufferSize];

int size = 0;

int length = 0;

/* 从文件读取数据至缓冲区 */

while ((length = fStream.read(buffer)) != -1) {

/* 将资料写入DataOutputStream中 */

ds.write(buffer, 0, length);

size = size &#; length;

}

sb = newStringBuilder();

sb.append(end);

ds.write(sb.toString().getBytes());

fStream.close();

}

//表单结束标志

sb.append(prefix);

sb.append(boundary);

sb.append(prefix);

sb.append(end);

ds.write(sb.toString().getBytes());

/* close streams*/

ds.flush();

//

// /* 取得Response内容 */

int res=con.getResponseCode();

if(res!=){

//由后台程序提交

LogService.getInstance().recordLog("存入数据库的提交地址为:"&#;posturl&#;" n提交的数据为:"&#;JSonUtil.tojson(postparam)&#;" n附件:"&#;JSonUtil.tojson(postfile));

putTODB(posturl, postparam,postfile, type);

//adapter.close();

ds.close();

con.disconnect();

return 1;

}else{

if(!type.equals("0")){//编码

String s ="";

InputStreamReader isr =newInputStreamReader(con.getInputStream(),"UTF-8");

int i ;

while((i=isr.read())!=-1){

s=s&#;(char)i;

}

String result =ParseResponseMessage.Parse(s);

ds.close();

con.disconnect();

if(result.equals("0")){

//提交成功

return 0;

}else{

//服务端提交没有成功

return -1;

}

}else{

//不编码方式

return ;

}

}

}catch(SocketTimeoutException cone){

//网络连接超时

putTODB(posturl, postparam,postfile, type);

return -2;

}

catch (Exception e) {

return -1;

}

}

private static void showDialog(String mess)

{

new AlertDialog.Builder(context).setTitle("来自服务器的消息")

.setMessage(mess)

.setNegativeButton("确定",newDialogInterface.OnClickListener()

{

public void onClick(DialogInterface dialog,int which)

{

}

})

.show();

}

/**

* 向服务器发送请求,如果发送不成功,将会自动存入到数据库中,由线程在后台自动提交

* @paramposturl 要提交数据的url地址,如 * @parampostparam 要提交的form中的参数(名&#;对)

* @parampostfile 要提交的form中的文件参数(form中控件名,上传的文件路径全名名&#;对)

* @paramtype 暂时设置为"1",为保证紧急消息最先执行数&#;越大表示越紧急;(0为向蒋勇的工程提交)

* @return0数据发送成功 1 数据发送不成功,由后台线程去自动提交 -1提交出现异常

*/

public static synchronized int Post(String posturl,Map<String,String> postparam,Map<String,String> postfile,String type){

//检查网络状态

if(!SysConfig.netWorkIsOK){

putTODB(posturl, postparam,postfile,type);

return 2;

}else{

if(postfile==null||postfile.isEmpty()){//不带附件

returnpostNotWithFile(posturl, postparam,postfile,type);

}else{

//带有附件

returnPostWithFile(posturl, postparam, postfile,type);

}

}

}

private static int postNotWithFile(String posturl,

Map<String,String> postparam,Map<String,String> postfile,String type) {

DefaultHttpClient httpClient =newDefaultHttpClient(httpParams);

HttpPost httpRequest =newHttpPost(posturl);

List<NameValuePair> localparams =newArrayList<NameValuePair>();

for (Map.Entry<String,String> entry : postparam.entrySet()) {

if(type.equals("0")){//不编码

localparams.add(newBasicNameValuePair(entry.getKey(),entry.getValue()));

}else{//编码

localparams.add(newBasicNameValuePair(entry.getKey(),StringUtil

.StringToHex(entry.getValue())));

}

}

try {

httpRequest

.setEntity((HttpEntity)newUrlEncodedFormEntity(

localparams, HTTP.UTF_8));

HttpResponse httpResponse = httpClient.execute(httpRequest);

// 发送不成功,存入数据库中

if (httpResponse.getStatusLine().getStatusCode() != ) {

LogService.getInstance().recordLog("存入数据库的提交地址为:"&#;posturl&#;" n提交的数据为:"&#;JSonUtil.tojson(postparam)&#;" n附件:"&#;JSonUtil.tojson(postfile));

putTODB(posturl, postparam,postfile, type);

//adapter.close();

return 1;

} else {

//解析返回的字符串编码

if(!type.equals("0")){//编码

String result=EntityUtils.toString(httpResponse.getEntity());

result =ParseResponseMessage.Parse(result);

if(result.equals("0")){

//提交成功

return 0;

}else{

//服务端提交没有成功

return -1;

}

}else{//不编码

String result=EntityUtils.toString(httpResponse.getEntity());

// showDialog(result);

return ;

}

}

}

catch(SocketTimeoutException cone){

//网络连接超时

putTODB(posturl, postparam,postfile, type);

return -2;

}

catch (Exception e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

return -1;

}

}

private static void putTODB(String posturl,Map<String,String> postparam,Map<String,String> postfile,String type) {

PostURL aposturl =newPostURL();

if(type==null||type.equals("")){

type="0";

}

aposturl.setData_type(type);

aposturl.setExecute_status(0);

aposturl.setPosturl(posturl);

aposturl.setParams(postparam);

aposturl.setFiles(postfile);

aposturl.prepare();

adapter.insert(aposturl);

}

private PostURL[] getData(){

returnadapter.QueryData("execute_status!= 1","data_type");

// return adapter.QueryData("", "data_type");

}

public void run(){

while(true){

//检测网络状态是否可用

if(SysConfig.netWorkIsOK ==true){

//检查是否有数据需要发送

//取出数据

posturls =getData();

if(posturls!=null){

for(int i=0;i<posturls.length;i&#;&#;){

PostURL vo =posturls[i];

//将参数恢复成Map

vo.resume();

if(vo.getFiles()!=null&&!vo.getFiles().isEmpty()){

//有附件

String end ="rn";

String prefix ="--";

String boundary ="*****";

try {

URL url =newURL(vo.getPosturl());

HttpURLConnection con = (HttpURLConnection) url.openConnection();

StringBuilder sb =newStringBuilder();

FileInputStream fStream=null;

/* 允许Input、Output,不使用Cache */

con.setConnectTimeout(SysConfig.nConnectionTimeout);

con.setReadTimeout(SysConfig.readFileTimeout);

con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

/* 设置传送的method=POST */

con.setRequestMethod("POST");

/*setRequestProperty */

con.setRequestProperty("Connection","keep-alive");

con.setRequestProperty("Charset","UTF-8");

con.setRequestProperty("Content-Type",

"multipart/form-data;boundary=" &#; boundary);

// // 拼接参数(不包括文件)

List<NameValuePair> localparams =newArrayList<NameValuePair>();

for (Map.Entry<String,String> entry : vo.getParams().entrySet()) {

sb.append(prefix);

sb.append(boundary);

sb.append(end);

sb.append("Content-Disposition:form-data;name="" &#; entry.getKey()

&#; """&#;end&#;"Content-Type:text/plain;Charset=UTF-8"&#;end );

if(vo.getData_type().equals("0")){//不编码

sb.append("Content-Transfer-Encoding:8bit"&#;end&#;end&#; entry.getValue() &#; end);

}else{

//编码 sb.append("Content-Transfer-Encoding:8bit"&#;end&#;end&#; ((entry.getValue()==null||entry.getValue().equals(""))?StringUtil.StringToHex(""):StringUtil.StringToHex(entry.getValue()))&#; end);

}

}

// /* 设置DataOutputStream */

DataOutputStream ds =newDataOutputStream(con.getOutputStream());

Stringt=sb.toString();

ds.write(sb.toString().getBytes());

//发送文件

for (Map.Entry<String,String> entry : vo.getFiles().entrySet()) {

sb = newStringBuilder();

sb.append(prefix);

sb.append(boundary);

sb.append(end);

sb.append("Content-Disposition:form-data;name=""

&#; entry.getKey()

&#; "";filename=""

&#; entry.getValue().substring(

entry.getValue().lastIndexOf('/') &#; 1) &#;"""

&#; end);

sb.append("Content-Type:application/octet-stream;Charset=UTF-8"

&#; end &#; end);

ds.write(sb.toString().getBytes());

/* 取得文件的FileInputStream */

fStream = newFileInputStream(entry.getValue());

/* 设置每次写入bytes */

int bufferSize = ;

byte[] buffer =newbyte[bufferSize];

int size = 0;

int length = 0;

/* 从文件读取数据至缓冲区 */

while ((length = fStream.read(buffer)) !=-1) {

/*将资料写入DataOutputStream中 */

ds.write(buffer, 0, length);

size = size &#; length;

}

sb = newStringBuilder();

sb.append(end);

fStream.close();

}

//表单结束标志

sb.append(prefix);

sb.append(boundary);

sb.append(prefix);

sb.append(end);

ds.write(sb.toString().getBytes());

/* closestreams */

ds.flush();

//

// /* 取得Response内容 */

int res=con.getResponseCode();

if(res!=){

//不成功

vo.setExecute_status(-1);

adapter.updateOneData(vo.getId(), vo);

ds.close();

con.disconnect();

}else{

adapter.deleteOneData(vo.getId());

ds.close();

con.disconnect();

}

}

catch(SocketTimeoutException cone){

//网络连接超时

}

catch (Exception e) {

//提交的表单有问题,为不让线程一直跑无效的数据,把该条记录删除

adapter.deleteOneData(vo.getId());

e.printStackTrace();

}

}else{

//没有附件

httpClient = newDefaultHttpClient(httpParams);

httpRequest = newHttpPost(vo.getPosturl());

List<NameValuePair> localparams =newArrayList<NameValuePair>();

for (Map.Entry<String,String> entry : vo.getParams().entrySet()) {

if(vo.getData_type().equals("0")){//不编码

localparams.add(newBasicNameValuePair(entry.getKey(), entry.getValue()));

}else{//编码

localparams.add(newBasicNameValuePair(entry.getKey(),StringUtil

.StringToHex(entry.getValue())));

}

}

try {

httpRequest

.setEntity((HttpEntity)newUrlEncodedFormEntity(

localparams, HTTP.ISO__1));

HttpResponse httpResponse = httpClient.execute(httpRequest);

// 发送不成功,存入数据库中

if(httpResponse.getStatusLine().getStatusCode() != ) {

vo.setExecute_status(-1);

adapter.updateOneData(vo.getId(), vo);

} else {

adapter.deleteOneData(vo.getId());

}

}

catch(SocketTimeoutException cone){

//网络连接超时

}

catch (Exception e) {

// TODO Auto-generatedcatch block

adapter.deleteOneData(vo.getId());

e.printStackTrace();

}

}

}

}else{

//检查主应用程序是否退出了

if(SysConfig.isActivety!=true){

//线程结束发送数据,关闭数据库

adapter.close();

break;

}else{

try {

Thread.sleep(SysConfig.PostTime);

} catch (InterruptedException e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

}

}

}

}else{

try {

Thread.sleep(SysConfig.PostTime);

} catch (InterruptedException e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

}

}

}

}

}

8.Reader工具

public class IniReader {

private HashMap<String,String> sections =newHashMap();

public IniReader(String filename)throws IOException {

BufferedReader reader =newBufferedReader(newInputStreamReader(

new FileInputStream(filename), "UTF-8"));

read(reader);

reader.close();

}

private void read(BufferedReader reader)throws IOException {

String line;

while ((line = reader.readLine()) !=null) {

parseLine(line);

}

}

private void parseLine(String line) {

if (line.matches(".*=.*")) {

int i = line.indexOf('=');

String name = line.substring(0, i);

String value = line.substring(i &#; 1);

name = name.trim();

value = value.trim();

sections.put(name, value);

}

}

public String getValue(String name,String defalut) {

String value = (String) sections.get(name);

if (value ==null) {

return defalut;

}

return value;

}

}

9.Android数据库DBOpenhelper(数据库建在指定路径下)1.DBopenhelper

packagenci.dsp.db;

import nci.dsp.config.SysConfig;

import android.content.Context;

importandroid.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

importandroid.database.sqlite.SQLiteDatabase.CursorFactory;

public class DBOpenHelper extendsSDSQLiteOpenHelper{

privatestatic final String DB_NAME=SysConfig.db_dictory;

privatestatic final String DB_POSTURL_TABLE ="posturl";

privatestatic final int DB_VERSION =1;

privatestatic final String DB_POSTURL_CREATE ="create table posturl (_id integerprimary key autoincrement,data_type text,posturl text,params text,filestext,execute_status integer);";

privatestatic final String DB_FAVOR_ADDRESS_CREATE ="create tablefavoraddress(_id integer primary key autoincrement,x text,y text,addressnametext);";

privatestatic final String DB_COMMANDTEMPLET_CREATE ="create table commandtemplet(_id integer primary key autoincrement,made_time text,templet_content_wholetext,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:接收到的命令

*/

privatestatic final String DB_COMMAND_CREATE ="create table command(_id integerprimary key autoincrement,command_id text," &#;

"establish_timetext,command_establish_man_id text,command_establish_man_nametext,command_establish_man_depart text," &#;

"command_establish_man_phonetext,command_receiver_man text,command_content text,attach text,posx text,posytext,type 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:接收到的任务反馈

*/

privatestatic final String DB_FEEDBACK_CREATE ="create table feedback(_id integerprimary key autoincrement,feedback_id text,command_id text," &#;

"feedback_timetext,feedback_man_name text,feedback_man_id text,feedback_man_departtext,feedback_man_phone text,feedback_content text,attach text,posx text,posytext,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:接收到的事件

*/

privatestatic final String DB_EVENT_CREATE ="create table event(_id integerprimary key autoincrement,event_id text,event_report_man_id text,event_report_man_name text,event_report_man_departtext,event_report_man_phone text,event_title text,event_content text,report_timetext,attach text,posx text,posy text,type integer);";

//友邻表

/**

* _id integer primary key autoincrement,主键

* neighbor_id text,友邻id

* neighbor_name text,友邻名字

* neighbor_type text,友邻类型(1:单位 0:个人)

* neighbor_phone text,友邻的电话号码

* posx text,友邻位置(在地图上显示的友邻位置,友邻位置的变化由一个线程获取,获取到位置后存入该表中)

* posy text友邻位置(在地图上显示的友邻位置,友邻位置的变化由一个线程获取,获取到位置后存入该表中)

*/

privatestatic final String DB_NEIGHBOR_CREATE ="create table neighbor(_id integerprimary key autoincrement,neighbor_id text,neighbor_name text,neighbor_typetext,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 联系人电话号码

*/

privatestatic final String DB_LINKMAN_CREATE="create table linkman(_id integer primary key autoincrement,linkman_idtext,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表获取具体的附件内容)

*/

privatestatic final String DB_PUBLIC_INFO_CREATE="create table publicinfo(_idinteger primary key autoincrement,public_info_id text,public_info_typetext,public_info_title text,public_info_content text,public_info_origintext,attach_count integer);";

//公共信息附件表

/**

* _id integer primary key autoincrement,主键

* public_info_id text,公共信息ID号

* attach_name text,附件的名字

* attach_file text 附件文件的地址(接收到的文件存放到/sdcard/td_pda/publicinfo 目录下,所有的文件统一以数字(存储时的时间)命名)

*/

privatestatic final String DB_PUBLIC_INFO_ATTACH_CREATE="create tablepublicinfoattach(_id integer primary key autoincrement,public_info_idtext,attach_name text,attach_file text);";

publicDBOpenHelper(Context context, String name,

CursorFactoryfactory, int version) {

super(context,name, factory, version);

//TODO Auto-generated constructor stub

}

@Override

publicvoid onCreate(SQLiteDatabase _db) {

//TODO Auto-generated method stub

_db.execSQL(DB_POSTURL_CREATE);

_db.execSQL(DB_COMMANDTEMPLET_CREATE);

_db.execSQL(DB_FAVOR_ADDRESS_CREATE);

_db.execSQL(DB_COMMAND_CREATE);

_db.execSQL(DB_FEEDBACK_CREATE);

_db.execSQL(DB_EVENT_CREATE);

_db.execSQL(DB_NEIGHBOR_CREATE);

_db.execSQL(DB_LINKMAN_CREATE);

_db.execSQL(DB_PUBLIC_INFO_CREATE);

_db.execSQL(DB_PUBLIC_INFO_ATTACH_CREATE);

}

@Override

publicvoid onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {

//TODO Auto-generated method stub

_db.execSQL("DROPTABLE IF EXISTS posturl");

_db.execSQL("DROPTABLE IF EXISTS favoraddress");

_db.execSQL("DROPTABLE IF EXISTS commandtemplet");

_db.execSQL("DROPTABLE IF EXISTS command");

_db.execSQL("DROPTABLE IF EXISTS feedback");

_db.execSQL("DROPTABLE IF EXISTS event");

_db.execSQL("DROPTABLE IF EXISTS neighbor");

_db.execSQL("DROPTABLE IF EXISTS linkman");

_db.execSQL("DROPTABLE IF EXISTS publicinfo");

_db.execSQL("DROPTABLE IF EXISTS publicinfoattach");

onCreate(_db);

}

}

2. SDDBopenhelper

import java.io.File;

import nci.dsp.config.SysConfig;

import android.content.Context;

importandroid.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteException;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.util.Log;

public abstract class SDSQLiteOpenHelper{

private static final String TAG = SDSQLiteOpenHelper.class.getSimpleName();

private final Context mContext;

private final String mName;

private final CursorFactory mFactory;

private final int mNewVersion;

private SQLiteDatabase mDatabase = null;

private boolean mIsInitializing = false;

public SDSQLiteOpenHelper(Context context,String name,

CursorFactory factory,int version) {

if(version<1 )thrownewIllegalArgumentException ("Version must be >=1,was "&#;version);

mContext= context;

mName= name;

mFactory= factory;

mNewVersion=version;

}

public synchronized SQLiteDatabase getWritableDatabase(){

if(mDatabase !=null&&mDatabase.isOpen()&&!mDatabase.isReadOnly()){

return mDatabase;

}

if(mIsInitializing){

throw new IllegalStateException("getWritableDatabase calledrecursively");

}

boolean success =false;

SQLiteDatabase db =null;

try{

mIsInitializing= true;

if(mName ==null){

db= SQLiteDatabase.create(null);

}else{

String path =getDatabasePath(mName).getPath();

db=SQLiteDatabase.openOrCreateDatabase(path, mFactory);

}

int version = db.getVersion();

if(version!=mNewVersion){

db.beginTransaction();

try{

if(version==0){

onCreate(db);

}else{

onUpgrade(db,version,mNewVersion);

}

db.setVersion(mNewVersion);

db.setTransactionSuccessful();

}finally{

db.endTransaction();

}

}

onOpen(db);

success=true;

return db;

}finally{

mIsInitializing= false;

if(success){

if(mDatabase!=null){

try{

mDatabase.close();

}catch(Exception e){

}

}

mDatabase=db;

}else{

if(db!=null) db.close();

}

}

}

public synchronized SQLiteDatabase getReadableDatabase(){

if(mDatabase !=null&&mDatabase.isOpen()){

return mDatabase;

}

if(mIsInitializing){

throw new IllegalStateException("getReadableDatabase calledrecursively");

}

if(mName ==null)returnnull;

SQLiteDatabase db =null;

try{

mIsInitializing= true;

String path =getDatabasePath(mName).getPath();

db= SQLiteDatabase.openDatabase(path, mFactory,SQLiteDatabase.OPEN_READWRITE);

if(db.getVersion()!= mNewVersion){

throw new SQLiteException("Can't upgrade read-only database fromversion "&#;db.getVersion()&#;" to "&#;mNewVersion&#;" : "&#;path);

}

onOpen(db);

Log.w(TAG,"Opened "&#;mName&#;" in read-only mode");

mDatabase= db;

return mDatabase;

}finally{

mIsInitializing=false;

if(db!=null&&db!=mDatabase)db.close();

}

}

public synchronized void close(){

if(mIsInitializing)thrownewIllegalStateException ("Closed during initialization");

if(mDatabase!=null&&mDatabase.isOpen()){

mDatabase.close();

mDatabase= null;

}

}

public File getDatabasePath(String name){

return new File("/sdcard/"&#;name);

}

public abstract void onCreate(SQLiteDatabase db);

public abstract void onUpgrade(SQLiteDatabase _db,int oldVersion,int newVersion) ;

public void onOpen(SQLiteDatabase db){}

}

.提示框

Builder builder = newAlertDialog.Builder(this);

builder.setView(some_View);

builder.setPositiveButton("查看",newDialogInterface.OnClickListener() {

public void onClick(DialogInterfacedialoginterface,int i) {

}

}).setNegativeButton("关闭",newDialogInterface.OnClickListener() {

public void onClick(DialogInterface dialoginterface,int i) {

}

}).show();

.读写操作

out = new FileOutputStream(file);

infoToWrite= infoToWrite&#;String.valueOf(infro);

out.write(infoToWrite.getBytes());

out.flush();

out.close();

in= new FileInputStream(file);

byte[] temp =newbyte[in.available()];

while (in.read(temp)!=-1){

}

display = new String(temp);

.写日志实例

public class LogService {

privatestatic String TAG ="LogService";

privateSimpleDateFormat mylogsdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

private static OutputStreamWriter writer;

privatestatic LogService instance = null;

public static synchronized LogService getInstance()

{

if(instance == null)

{

try{

String Logpath=SysConfig.LogPath;

//判断文件是否存在,不存则新建,存在就在文件后面追加日志

File logFile = newFile(Logpath);

if(logFile.exists()){

long filesize=logFile.length();

if(filesize>**){

//如果大于M进行日志清理

logFile.delete();

writer= new OutputStreamWriter(newFileOutputStream(Logpath));

}else{

writer= new OutputStreamWriter(newFileOutputStream(Logpath,true));

}

}

else{

writer= new OutputStreamWriter(newFileOutputStream(Logpath));

}

}catch(Exception e){

Log.e(TAG,e.getMessage());

}

instance = new LogService();

}

return instance;

}

public synchronized void recordLog(String msg){

android 常用代码(安卓通用代码)

if(SysConfig.isRecordLog){

if(writer!=null){

try{

Datetime = new Date();

writer.write(mylogsdf.format(time)&#;""&#;msg);

writer.write("n");

writer.flush();

}catch(IOExceptione){

Log.e(TAG,e.getMessage());

}

}

}

}

}

.发送和接收短信

接收短信

private String strACT ="android.provider.Telephony.SMS_RECEIVED";

if (intent.getAction().equals(strACT)) {

Bundle bundle = intent.getExtras();

if (bundle !=null) {

Object[] pdus = (Object[]) bundle.get("pdus");

SmsMessage[] msg =newSmsMessage[pdus.length];

for (int i = 0; i < pdus.length; i&#;&#;) {

msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

}

content = msg[0].getMessageBody();

}

发送短信

private void sendSMS(String phone,String message) {

// PendingIntent Pi =PendingIntent.getActivity(this, 0, new

// Intent(this,

// telecontrol.class), 0);

SmsManager sms =SmsManager.getDefault();

sms.sendTextMessage(phone,null, message,null,null);

}

.定时器

TimerTask task =new TimerTask() {

public void run() {

}

}

Timer timer = new Timer(true);

timer.schedule(task,0,);

.EditText的常用操作

EditText input = new EditText(this);

//只能输入数字

input.setKeyListener(new DigitsKeyListener());

//控制输入长度

input.setFilters(newInputFilter[]{newInputFilter.LengthFilter()});

/******************************************************/

//监控字符变化 input.addTextChangedListener(newDSPTextWatcher());

public class DSPTextWatcher implements TextWatcher {

public void afterTextChanged(Editable arg0) {

// TODO Auto-generatedmethod stub

Dosomethings();

}

public void beforeTextChanged(CharSequence arg0,int arg1,int arg2, int arg3) {

// TODO Auto-generatedmethod stub

Dosomethings();

}

public void onTextChanged(CharSequence arg0,int arg1,int arg2,

int arg3) {

// TODO Auto-generatedmethod stub

Dosomethings();

}

}

/******************************************************/

//字符置顶

mater_use_input.setGravity(Gravity.TOP);

getWindow().setSoftInputMode(

WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

mater_use_input.setOnTouchListener(newView.OnTouchListener() {

@Override

public boolean onTouch(View arg0,MotionEvent arg1) {

getWindow().setSoftInputMode(WindowManager.LayoutParams.

SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

return false;

}

});

//获取光标位置插入字符等

EditText describe = new EditText (this);

String content=“test”;

//获得当前光标位置

int current_position = describe.getSelectionStart();

StringBuffer text =newStringBuffer(describe.getText().toString());

text.insert(current_position, content);

describe.setText(text);

//得到添加插入后的光标位置

int pos = current_position &#; templetcontent.length();

Selection.setSelection(command_describe.getText(), pos);

.时间的唯一标识符和UUID

Date timer = new Date();

Long id = timer.getdate();

Long id2 = System.currentTimeMillis();

String uuid =java.util.UUID.randomUUID().toString();

.跨包启动ACTIVITY

ComponentName cn =newComponentName("com.phd.camera",

"com.phd.camera.TDCamera");

intent.setComponent(cn);

startActivityForResult(intent, 1);

.Activity LaunchMode四种模式

android:launchMode="standard"

//默认模式,点击5次打开五个ACTIVITY,重载

android:launchMode="singleTop"

//只存在一个ACTIVITY如果在栈顶不重载,否则重载

android:launchMode="singleTask"

//只存在一个ACTIVITY,不重载

android:launchMode="singleInstance"

//至存在一个ACTIVITY,不重载

.关闭全部程序

final ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

am.restartPackage(getPackageName());

.附件预览VIDEO,TXT,PIC

public class FilePreview extends Activity {

privateBitmap bm = null;

privatedouble currscale=1;

privateImageView iView;

privateScrollView sv ;

privateDisplayMetrics dm;

privateint offx=0;

privateint offy=0;

privateButton big,small;

privateString attachType="";

privatevoid small() {

intwidth = bm.getWidth();

intheight = bm.getHeight();

doublescale = 0.8;

if(currscale<0.2){

small.setBackgroundResource(R.drawable.zoom_out_up_un);

}else{

currscale=currscale*scale;

big.setBackgroundResource(R.drawable.zoom_in_up);

}

Matrixmatrix = new Matrix();

matrix.postScale((float)currscale,(float)currscale);

Bitmapresizebm= Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

iView.setImageBitmap(resizebm);

}

privatevoid big() {

intwidth = bm.getWidth();

intheight = bm.getHeight();

doublescale = 1.;

if(currscale>2){

big.setBackgroundResource(R.drawable.zoom_in_up_un);

}else{

currscale=currscale*scale;

small.setBackgroundResource(R.drawable.zoom_out_up);

}

Matrixmatrix = new Matrix();

matrix.postScale((float)currscale,(float)currscale);

Bitmapresizebm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

iView.setImageBitmap(resizebm);

;

}

publicvoid onCreate(Bundle savedInstanceState){

longattachBeginTime=System.currentTimeMillis();

super.onCreate(savedInstanceState);

LogService.getInstance().recordLog("打开FilePreview!");

setTitle("附件预览");

sv=new ScrollView(FilePreview.this);

LinearLayoutout=new LinearLayout(FilePreview.this);

out.setOrientation(LinearLayout.VERTICAL);

Intentintent = getIntent();

Stringpath = intent.getStringExtra("preview_path");

intidx=path.indexOf(".");

Stringtype=path.substring(idx&#;1).toLowerCase();

//如果附件是图片

if(SysConfig.imgformat.contains(type)){

attachType="图片";

//获取屏幕分辨率,根据屏幕分辨率创建界面

dm= new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(dm);

//根据不同的屏幕显示不同

if(dm.heightPixels==&&dm.widthPixels==){//*竖屏幕

offx=;

offy=;

}

if(dm.heightPixels==&&dm.widthPixels==){//*横屏幕

offx=;

offy=;

}

if(dm.heightPixels==&&dm.widthPixels==){//*竖屏幕

offx=;

offy=;

}

if(dm.heightPixels==&&dm.widthPixels==){//*横屏幕

offx=;

offy=;

}

//布局

AbsoluteLayout aLayout = new AbsoluteLayout(this);

aLayout.setBackgroundColor(Color.parseColor(SysConfig.backgroundColor));

AbsoluteLayout.LayoutParamsAbsLayoutParam = new AbsoluteLayout.LayoutParams(

AbsoluteLayout.LayoutParams.FILL_PARENT,AbsoluteLayout.LayoutParams.FILL_PARENT, 0, );

AbsoluteLayout.LayoutParamsAbsLayoutParam2 = new AbsoluteLayout.LayoutParams(

AbsoluteLayout.LayoutParams.FILL_PARENT,AbsoluteLayout.LayoutParams.FILL_PARENT, (dm.widthPixels-offx),(dm.heightPixels-offy));

AbsoluteLayout.LayoutParamsAbsLayoutParamListBig = new AbsoluteLayout.LayoutParams(

,, (dm.widthPixels-offx), 0);

AbsoluteLayout.LayoutParamsAbsLayoutParamListSamll = new AbsoluteLayout.LayoutParams(

,, (dm.widthPixels-offx&#;), 0);

HorizontalScrollViewhscv= new HorizontalScrollView(this);

iView=newImageView(FilePreview.this);

bm=BitmapFactory.decodeFile(path);

iView.setImageBitmap(bm);

hscv.addView(iView);

sv.addView(hscv);

big= new Button(this);

big.setBackgroundResource(R.drawable.zoom_in_up);

big.setOnClickListener(newView.OnClickListener() {

@Override

publicvoid onClick(View arg0) {

//TODO Auto-generated method stub

big();

}

});

aLayout.addView(big,AbsLayoutParamListBig);

small= new Button(this);

small.setBackgroundResource(R.drawable.zoom_out_up);

small.setOnClickListener(newView.OnClickListener() {

@Override

publicvoid onClick(View arg0) {

//TODO Auto-generated method stub

small();

}

});

aLayout.addView(small,AbsLayoutParamListSamll);

aLayout.addView(sv,AbsLayoutParam);

aLayout.setBackgroundColor(Color.parseColor(SysConfig.backgroundColor));

setContentView(aLayout);

}else

//如果附件是音频 目前只支持3ga,mp3

if(SysConfig.audioformat.contains(type)){

attachType="音频";

VideoView v=newVideoView(FilePreview.this);

//指定地址

v.setVideoPath(path);

//设置播放条

v.setMediaController(newMediaController(this));

//开始播放

v.start();

out.addView(v);

out.setBackgroundColor(Color.parseColor(SysConfig.backgroundColor));

setContentView(out);

}else

//如果附件是视频 目前只支持3gp

if(SysConfig.vedioformat.contains(type)){

attachType="视频";

VideoView v=newVideoView(FilePreview.this);

//指定地址

v.setVideoPath(path);

//设置播放条

v.setMediaController(newMediaController(this));

//开始播放

v.start();

out.addView(v);

out.setBackgroundColor(Color.parseColor(SysConfig.backgroundColor));

setContentView(out);

}else

//如果附件是TXT&#;式文档

if(SysConfig.txtformat.contains(type)){

attachType="TXT";

TextView v=newTextView(FilePreview.this);

//读取txt中内容

File f=new File(path);

byte[]buffer = null;

try{

InputStreamin = new FileInputStream(f);

buffer= new byte[in.available()];

in.read(buffer);

}catch (FileNotFoundException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

Stringcontent = "";

try{

content = newString(buffer,"UTF-8");

}catch (UnsupportedEncodingException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

//设置内容

v.setText(content);

out.addView(v);

sv.addView(out);

out.setBackgroundColor(Color.parseColor(SysConfig.backgroundColor));

setContentView(sv);

}

else{

TextView v=newTextView(FilePreview.this);

v.setText("附件类型无法解析!");

out.addView(v);

out.setBackgroundColor(Color.parseColor(SysConfig.backgroundColor));

setContentView(out);

}

longattachEndTime=System.currentTimeMillis();

LogService.getInstance().recordLog(attachType&#;"附件预览界面打开时间为:"&#;(attachEndTime-attachBeginTime)&#;"微秒");

}

}

.刷新ListView的用法

SimpleAdapter adapter ;

HashMap<String,Object> map = (HashMap<String,Object>) adapter.getItem(selectedItem);

if(b)

map.put("img",R.drawable.ip);

else

map.put("img",R.drawable.zzw);

adapter.notifyDataSetChanged();

.SharedPreferences的用法

SharedPreferences有三种访问模式:私有(MODE_PRIVATE),全局读(MODE_WORLD_READABLE)和全局写(MODE_WORLD_WRITEABLE)

//私有模式 Public static int mode = MODE_PRIVATE;

//全局读写 Public static int mode = Context. MODE_WORLD_READABLE&#;Context.MODE_WORLD_WRITEABLE;

Public static final String PREFERENCE_NAME = “data”;

SharedPreferences sp = getSharedPreferences(PREFERENCE_NAME, mode);

//存储 SharedPreferences.Editor editor = sp.edit();

editor.putString(“name”,"open");

editor.putInt(“Age”,);

editor.putFloat(“Height”,1.f);

editor.commit();

//获取 String name = sp.getString(“name”,“default name”);

//获取别的包下的SharedPreferences

Public static final String preferences_package= “edu.cn.demo”;

Public static final String preferences_name = “data”;

Public static int mode = Context. MODE_WORLD_READABLE&#;Context.MODE_WORLD_WRITEABLE;

Try {

Contextc=this.createPackageContext(preferences_package,Context.CONTEXT_IGNORE_SECURITY);

}catch(){

}

SharedPreferences sp =c.getSharedPreferences(PREFERENCE_NAME, mode);

.Spinner的简单用法

//一种方法从R.String.Array配置

ArrayAdapter<?> adapter1 =ArrayAdapter.createFromResource(this,R.array.one, android.R.layout.simple_spinner_item);

//从ArrayList里面

ArrayList<String> one =newArrayList<String>();

one.add("one");

ArrayAdapter<?>adapter = newArrayAdapter<String>(this, android.R.layout.simple_spinner_item, one);

Spinners = new Spinner (this);

s.setAdapter(adapter);

.获取手机分辨率

DisplayMetrics dm =newDisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(dm);

参数X:dm.heightPixels 参数Y:dm.widthPixels

.解析XML文件

private List<SoftResourcePO> getAllSoftResourceByModifyXml() {

LogService.getInstance().recordLog("读取本地资源文件!");

List<SoftResourcePO> softs =newArrayList<SoftResourcePO>();

SAXReader reader =newSAXReader();

Document doc = null;

try {

doc = reader.read(newBufferedReader(newInputStreamReader(

new FileInputStream(XMLADDRESS),

"GBK")));

} catch (Exception e) {

e.printStackTrace();

}

Element rootElement = doc.getRootElement();

List elements = rootElement.elements();

for (Object o : elements) {

Element element = (Element) o;

if (element.getName().equals("row")) {

List values = element.elements();

SoftResourcePO softPO =newSoftResourcePO();

softPO.setSeq_id(Long.parseLong(((Element) values.get(0))

.getText()));

softPO.setSoftresource_no(((Element) values.get(1)).getText());

softPO

.setSoftresource_name(((Element) values.get(2))

.getText());

softPO

.setSoftresource_desc(((Element) values.get(3))

.getText());

softPO.setSoftresource_address_device(((Element) values.get(4))

.getText());

softPO.setSoftresource_orderno(Integer

.parseInt(((Element) values.get(5)).getText()));

softPO.setSoftresource_icon_chr(((Element) values.get(6))

.getText());

softPO.setSoftresource_icon_chr_offline(((Element) values

.get(7)).getText());

softPO.setSoftresource_fatherno(Long

.parseLong(((Element) values.get(8)).getText()));

softPO.setIf_offline(Integer.parseInt(((Element) values.get(9))

.getText()));

softs.add(softPO);

}

}

return softs;

}

.根据图片名称找到对应R里面的&#;

Button.setImageResource(R.drawable.class.getField(pic_name).getInt(0) );

.监听网络连接

public classConnectionChangeReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context,Intent arg1) {

// TODO Auto-generated method stub

ConnectivityManager connetivityManager=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetInfo =connetivityManager.getActiveNetworkInfo();

//NetworkInfo mobNetInfo =connetivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if(activeNetInfo!=null){

//判断设置网络是否可用 activeNetInfo.isConnected();

}

}

}

.获取Strings.XML,R.array.one内容

String arr[] =getResources().getStringArray(R.array.one);

.打开系统自带的相册并返回所选图像

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.addCategory(Intent.CATEGORY_OPENABLE);

intent.setType("image/*");

intent.putExtra("return-data","true");

startActivityForResult(intent,0);

if (requestCode == 0) {

Bitmap cameraBitmap = (Bitmap)data.getExtras().get("data");

Uri uri = data.getData();

String[] proj = {MediaStore.Images.Media.DATA};

Cursor cursor = managedQuery(uri, proj,null,null,null);

int column_index =cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

cursor.moveToFirst();

path = cursor.getString(column_index);

}

.根据颜色&#;着色

View.setBackgroundColor(Color.parseColor(#ffffff));

1.

2.

3.

4.

5.

6.

7.

8.

9.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

. Makejar的2种方法1) JAVA代码加校验实现

///jar cvf name.war

import javax.swing.*;

import javax.swing.border.EmptyBorder;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Calendar;

import java.util.HashMap;

import java.util.Map;

import java.util.jar.*;

public class MakeJAR extends JFrame {

/**

* 提供两个方法, 1.MakeJAR(),支持界面选择输入路径和输出路径; 2.MakeJAR(String dirfile, String

* targetfile),dirfile为打包目录的路径;targetfile为输出路径。

*/

privatestatic final long serialVersionUID = 1L;

privatestatic JarOutputStream jos;

privatestatic byte buf[] = new byte[];

privatestatic int len;

privatestatic int totalFileCount;

privatestatic int doneFileCount;

privateJTextField jarDirField;

privateJTextField jarTargetField;

privatestatic JProgressBar progressBar;

privatestatic ArrayList<String> filesList = new ArrayList<String>();;

privatestatic Map<String, String> valMap;

privatestatic HashMap<String, String> sections = new HashMap<String,String>();

publicstatic void main(String[] args) {

newMakeJAR();

}

//传两个参数:dirfile为要打包的路径;targetfile为输出路径。

publicMakeJAR(String dirfile, String targetfile) {

super("JAR Maker");

performed(dirfile,targetfile);

}

//从界面选择输入路径和输入路径

publicMakeJAR() {

super("JAR Maker");

valMap= new ValTypes().setTypes();

jarDirField= new JTextField();

jarTargetField= new JTextField();

finalJFileChooser jcdir = new JFileChooser();

finalJFileChooser jctar = new JFileChooser();

JButtondir = new JButton();

dir.setText("选择目录");

dir.addActionListener(newActionListener() {

publicvoid actionPerformed(ActionEvent e) {

jcdir.setFileSelectionMode(1);

jcdir.showOpenDialog(null);

jarDirField.setText(jcdir.getSelectedFile().getPath());

}

});

JButtontar = new JButton();

tar.setText("保存地址");

tar.addActionListener(newActionListener() {

publicvoid actionPerformed(ActionEvent e) {

jctar.setFileSelectionMode(1);

jctar.setAcceptAllFileFilterUsed(true);

jctar.showSaveDialog(null);

Calendarc = Calendar.getInstance();

Stringtime = new SimpleDateFormat("yyyyMMddHHmmss").format(c

.getTime());

jarTargetField.setText(jctar.getSelectedFile().getPath()&#; "\"

&#;time &#; ".war");

}

});

JPanelmainPanel = new JPanel();

mainPanel.setBorder(newEmptyBorder(3, 3, 3, 3));

mainPanel.setLayout(newBoxLayout(mainPanel, 1));

JPaneldirPanel = new JPanel();

JPaneltargetPanel = new JPanel();

dirPanel.setBorder(BorderFactory.createTitledBorder("输入操作的项目路径"));

targetPanel

.setBorder(BorderFactory.createTitledBorder("输入要打成的jar包的名称"));

dirPanel.add(jarDirField);

dirPanel.add(dir);

targetPanel.add(jarTargetField);

targetPanel.add(tar);

JPanelpanel3 = new JPanel();

panel3.setBorder(newEmptyBorder(5, 5, 5, 5));

panel3.setLayout(newBorderLayout());

JButtonstartButton = new JButton("打JAR包");

startButton.addActionListener(newActionListener() {

publicvoid actionPerformed(ActionEvent e) {

StringwfStr1 = new String(jarDirField.getText());

StringwfStr2 = new String(jarTargetField.getText());

performed(wfStr1,wfStr2);

}

});

panel3.add(startButton,"East");

mainPanel.add(dirPanel);

mainPanel.add(targetPanel);

mainPanel.add(panel3);

getContentPane().add(mainPanel);

pack();

Dimensionscreen = Toolkit.getDefaultToolkit().getScreenSize();

Dimensionsize = getSize();

setLocation((screen.width- size.width) / 2,

(screen.height- size.height) / 2);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

}

publicstatic void makeZip(File directory, File zipFile)

throwsIOException, FileNotFoundException {

jos= new JarOutputStream(new FileOutputStream(zipFile));

StringfileNames[] = directory.list();

if(fileNames != null) {

for(int i = 0; i < fileNames.length; i&#;&#;)

recurseFiles(newFile(directory, fileNames[i]), "");

}

jos.close();

}

privatestatic void recurseFiles(File file, String pathName)

throwsIOException, FileNotFoundException {

if(file.isDirectory()) {

pathName= pathName &#; file.getName() &#; "/";

jos.putNextEntry(newJarEntry(pathName));

StringfileNames[] = file.list();

if(fileNames != null) {

for(int i = 0; i < fileNames.length; i&#;&#;)

recurseFiles(newFile(file, fileNames[i]), pathName);

}

}else {

Stringfilename = file.getName();

StringversionTemp = valMap.get(filename);

if(versionTemp != null) {

Stringversion = getJarVersion(file.getPath());

inttemp = compareVersion(versionTemp, version);

Stringresult = temp == 0 ? "通过" : "未通过";

System.out.println(filename&#; "的校验结果为:" &#; result);

if(temp == -1) {

filesList.add(filename);

}

}

JarEntryjarEntry = new JarEntry(pathName &#; filename);

System.out.println(pathName&#; " " &#; filename);

FileInputStreamfin = new FileInputStream(file);

BufferedInputStreamin = new BufferedInputStream(fin);

jos.putNextEntry(jarEntry);

while((len = in.read(buf)) >= 0)

jos.write(buf,0, len);

in.close();

jos.closeEntry();

doneFileCount&#;&#;;

progressBar.setValue(doneFileCount);

}

}

publicvoid performed(String dirfile, String targetfile) {

StringwfStr1 = dirfile;

StringwfStr2 = targetfile;

finalFile jarDir = new File(wfStr1);

//int temp = wfStr2.trim().lastIndexOf(".");

//if (temp != -1) {

//wfStr2 = wfStr2.substring(0, temp);

//}

finalFile jarFile = new File(wfStr2);

if(!(new File(jarDir, "WEB-INF")).exists()) {

Stringmsg = "无效的路径,请重新选择!";

JOptionPane.showMessageDialog(MakeJAR.this,msg, "Error!", 0);

}else if (wfStr2.trim().equals("")) {

Stringmsg = "名称无效,请重新输入!";

JOptionPane.showMessageDialog(MakeJAR.this,msg, "Error", 0);

}else {

countFiles(jarDir);

progressBar= new JProgressBar(0, totalFileCount);

progressBar.setValue(0);

progressBar.setStringPainted(true);

setVisible(false);

getContentPane().removeAll();

JPanelpanel = new JPanel();

panel.add(progressBar);

getContentPane().add(panel);

pack();

setVisible(true);

Threadt = new Thread() {

publicvoid run() {

try{

makeZip(jarDir,jarFile);

if(filesList.size() < 1) {

Stringmsg = "jar包已保存到: "

&#;jarFile.getCanonicalPath();

JOptionPane.showMessageDialog(MakeJAR.this,msg,

"打包成功",-1);

}else {

StringmeString = "";

for(int i = 0; i < filesList.size(); i&#;&#;) {

meString= meString &#; filesList.get(i) &#; ";";

}

Stringmsg = "下列Jar包的版本低可能导致程序不能正常运行:"

&#;meString.substring(0,

meString.length()- 1);

JOptionPane.showMessageDialog(MakeJAR.this,msg,

"校验失败",-1);

//jarFile.delete();

}

}catch (Exception e) {

System.err.println(e);

}

System.exit(0);

}

};

t.start();

}

}

//private void performed(String wfStr1, String wfStr2) throws IOException {

//

//Runtime.getRuntime().exec("jar -cvf "&#;wfStr1&#;""&#;wfStr2&#;"/*");

//}

//比较版本号,-1表示版本低或者不匹配,0表示版本匹配

privatestatic int compareVersion(String version1, String version2) {

if(version1 != null && version2 != null) {

String[]arr1 = version1.trim().split("\.");

String[]arr2 = version2.trim().split("\.");

intmax = Math.min(arr1.length, arr2.length);

for(int i = 0, i1 = 0; i <= max; i&#;&#;) {

if(i == arr2.length) {

returni == arr1.length ? 0 : -1;

}else if (i == arr1.length) {

return0;

}else {

i1= arr2[i].compareTo(arr1[i]);

if(i1 > 0) {

return 0;

}else if (i1 < 0) {

return-1;

}

}

}

}

return-1;

}

privatestatic String getJarVersion(String path) {

try{

Stringfilename = "META-INF/MANIFEST.MF";

JarFilejarFile = new JarFile(path);

//Enumeration enms = jarFile.entries();

//while (enms.hasMoreElements()) {

//JarEntry entry = (JarEntry) enms.nextElement();

//String name = entry.getName();

//if (name.equals(filename))

//break;

//}

JarEntryentry = jarFile.getJarEntry(filename);

InputStreaminput = jarFile.getInputStream(entry);

InputStreamReaderisr = new InputStreamReader(input);

BufferedReaderreader = new BufferedReader(isr);

Stringline;

while((line = reader.readLine()) != null) {

parseLine(line);

}

reader.close();

Stringvalue = sections.get("Implementation-Version");

System.out.println("jar包的版本型号为:"&#; value);

returnvalue;

}catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

returnnull;

}

}

//解析Minifest的版本信息

privatestatic void parseLine(String line) {

//TODO Auto-generated method stub

if(line.matches(".*:.*")) {

inti = line.indexOf(":");

Stringname = line.substring(0, i);

Stringvalue = line.substring(i &#; 1);

name= name.trim();

value= value.trim();

sections.put(name,value);

}

}

privatevoid countFiles(File file) {

if(file.isDirectory()) {

StringfileNames[] = file.list();

if(fileNames != null) {

for(int i = 0; i < fileNames.length; i&#;&#;)

countFiles(newFile(file, fileNames[i]));

}

}else {

totalFileCount&#;&#;;

}

}

}

2) 命令代码实现

Runtime.getRuntime().exec("jar -cvf"&#;dirpath&#;" "&#; tarpath &#;"/*");

. create tablespace

create tablespace officedata

datafile 'e:oracleoradataofficedata.ora' size m

default storage(initial k

next k

pctincrease 0

minextents 1

maxextents unlimited)

. 获取URL信息

GetUrl.java

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URL;

public class GetUrl {

public static void main(String []args){

InputStream in = null;

OutputStream out = null;

try {

if((args.length!=1)&&(args.length!=2))thrownew IllegalArgumentException("Wrong number of args");

URL url = new URL(args[0]);

in = url.openStream();

if(args.length==2){

out = new FileOutputStream(args[1]);

}

else

out= System.out;

byte[] buffer =newbyte[];

int bytes_read;

while ((bytes_read=in.read(buffer))!=-1 ){

out.write(buffer,0,bytes_read);

}

} catch (Exception e) {

// TODO: handleexception

}finally{

try {

in.close();

out.close();

} catch (Exception e2) {

// TODO: handleexception

}

}

}

}

. 图片放大缩小适中屏幕

private Bitmap bm = null;

private double currscale=1;

private ScrollView sv ;

private DisplayMetrics dm;

dm = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(dm);

private void big or small() {

int width = bm.getWidth();

int height = bm.getHeight();

double scale = 1. or 0.8;

if(currscale>2 or <0.2){

big.setBackgroundResource(R.drawable.zoom_in_up_un);

big.setEnabled(false);

}else{

currscale =currscale*scale;

small.setBackgroundResource(R.drawable.zoom_out_up);

small.setEnabled(true);

}

Matrix matrix =newMatrix();

matrix.postScale((float)currscale, (float)currscale);

Bitmap resizebm =Bitmap.createBitmap(bm, 0, 0, width, height, matrix,false);

bmHeight = resizebm.getHeight();

bmWidth = resizebm.getWidth();

AbsLayoutParamPicture = new AbsoluteLayout.LayoutParams(

AbsoluteLayout.LayoutParams.FILL_PARENT,AbsoluteLayout.LayoutParams.FILL_PARENT, (dm.widthPixels -bmWidth)>0?(dm.widthPixels - bmWidth)/2:0,

(dm.heightPixels-offy--bmHeight)>0?&#;(dm.heightPixels-offy--bmHeight)/2:);

aLayoutPicture.removeView(sv);

iView.setImageBitmap(resizebm);

aLayoutPicture.addView(sv,AbsLayoutParamPicture);

}

. 文本文件翻页

//第一次显示

File f = new File(path);

fileOutStream =newRandomAccessFile(

f, "r");

fileOutStream.seek(perpageWord*position);

fileOutStream.read(buffer);

String content = new String(buffer,"UTF-8");

//翻页

private void showText(int add){

if(add==-1){

//-1:前一页

if(position>0){

byte[] buffer =newbyte[perpageWord];

position--;

try {

fileOutStream.seek(perpageWord*position);

fileOutStream.read(buffer);

String content =newString(buffer,"UTF-8");

v.setText(content);

} catch (IOException e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

}

}

if(perpageWord*(position&#;1)>=filetotleLength){

next.setEnabled(false);

}else{

next.setEnabled(true);

}

if(position==0){

prev.setEnabled(false);

}else{

prev.setEnabled(true);

}

return;

}

if(add==1){

//后一页

if(perpageWord*(position&#;1)<=filetotleLength){

byte[] buffer =newbyte[perpageWord];

position&#;&#;;

try {

fileOutStream.seek(perpageWord*position);

fileOutStream.read(buffer);

String content =newString(buffer,"UTF-8");

v.setText(content);

} catch (IOException e) {

// TODO Auto-generatedcatch block

e.printStackTrace();

}

}

if(perpageWord*(position&#;1)>=filetotleLength){

next.setEnabled(false);

}else{

next.setEnabled(true);

}

if(position==0){

prev.setEnabled(false);

}else{

prev.setEnabled(true);

}

return;

}

}

. 根据图片名称反射R的&#;

R.drawable.class.getField(picName).getInt(0);

Class c =Class.forName(address);

自定义jsp标签并在WebPageEditor中使用

by:changxw

前期准备

JSP自定义标签:在自定义标签的起始和结束标签之间的部分为标签体(Body)。

标签处理程序类:定义标签的行为,并在JSP引擎遇到自定义标签时调用执行。

标签库描述符(TLD)文件:描述标签库的XML文档,向JSP引擎提供有关自定义标签的标签处理程序的信息。tag标签相关属性:实现简单标签处理程序标签处理程序是一个在运行时调用的Java类,它包含在 JSP文件中使用的自定义标签的实现代码.标签处理程序必须实现或扩展javax.servlet.jsp包中的类和接口.javax.servlet.jsp含有允许标签处理程序类与JSP容器通信的接口和类。自定义标签已经早有接触了(Struts中使用了很多自定义标签,如html、bean等) 使用这种技术的优点:取代了JSP中的Java程序,并且可以重复使用,方便不熟悉Java编程的网页设计人员。

自定义标签

步骤1:

在eclipse3.4及以上javaEE版本中,

创建任意java工程,导入包javax.servlet.jsp.jar,

org.eclipse.jface.jar到工程。

步骤2:

在根目录创建包结构如下:

并在tlds包下创建相应的tld文件。

例如:box.tld

<?xmlversion="1.0"encoding="UTF-8"?>

<taglib uri="box"> //标签库根元素

<tlib-version>1.1.2</tlib-version>

<jsp-version>2.0</jsp-version>

<short-name>box</short-name>

<uri>box</uri> //uri标签库唯一标识

<description>box标签</description>

<!--盒子模型1-->

<tag> //标签定义

<name>box1</name> //标签名字

<tag-class>tagHandler.box.Box1</tag-class> //标签处理类全限定名

<body-content>empty</body-content> //标签体是否为空

<description>box1</description>

<attribute> //标签属性

<name>panelWidth</name> //属性名

<required>true</required> //当前属性是否必须填写,默认为false

</attribute> //<rtexprvalue>是否支持表达式输出

<attribute>

<name>panelHeight</name>

</attribute>

<attribute>

<name>whiteBg</name>

</attribute>

</tag>

</taglib>

步骤3:在src包下编写对应标签的处理类。

标签处理类需要继承SimpleTagSupport类,重写doTag()方法。

利用JspWriter写如标签的处理信息。

例如:

JspWriterout=getJspContext().getOut();”

out.write(“hello world”);

属性处理方法:

假如现在要自定义一个button标签,<inputtype=”button”>,我们可以直接写:

out.write(“<inputtype=”button”>”);即可

如果属性较少的话,我们可以在处理类中直接生成他们的get和set方法然后加入到字符串中。

但是如果标签的属性有很多怎么办?我们不可能都以硬编码的方式写,并且有些标签的属性并不一定会用到。

我这里是这样处理的:

定义一个Attributes类,将一些通用属性封装在本类中,用Map存储这些属性。

publicclassAttribute{

/**

* 使用两个Map分别存储属性的名称和属性&#;,以相同的key&#;控制对应关系,

* 因为此处依赖关系总是标签依赖Attribute类,用构造注入,以减少代码之间的耦合。

* Attribute类中定义的是大部分通用的属性

* @authorchangxw

*/

privatestaticStringcont;

publicMap<Integer,String>attribute=newHashMap<Integer,String>();//基本通用属性

staticpublicMap<Integer,String>names=newHashMap<Integer,String>();//属性的名称

static{

names.put(1,"type");

names.put(2,"value");

names.put(3,"onclick");

names.put(4,"id");

names.put(5,"style");

names.put(6,"title");

names.put(7,"accept");

names.put(8,"accesskey");

names.put(9,"align");

names.put(,"alt");

}

publicAttribute(Stringtype,

Stringvalue,Stringonclick,Stringid,Stringstyle,Stringtitle,Stringaccept,Stringaccesskey,

Stringalign,Stringalt){

attribute.put(1,type);

attribute.put(2,value);

attribute.put(3,onclick);

attribute.put(4,id);

attribute.put(5,style);

attribute.put(6,title);

attribute.put(7,accept);

attribute.put(8,accesskey);

attribute.put(9,align);

attribute.put(,alt);

}

/**

*

*@paramkey

*@return

*/

publicStringgetAttribute(Stringkey){

cont=attribute.get(key);

returncont;

}

}

这样在用到的时候可以在相应的标签处理类中传入相应的属性&#;即可。

下面在标签处理类中使用它:

处理类中仅需继承SimpleTagSupport类,重写doTag()方法,并封装所有属性,提供他们的get和set方法。

public class Date extends SimpleTagSupport{

Attribute att;

private boolean timeOnly;

@Override

publicvoiddoTag()throwsJspException,IOException{

//通过Attribute构造传入获取的属性&#;

att=newAttribute(getType(),getValue(),getOnclick(),getId(),getStyle(),getTitle(),getAccept(),getAccesskey(),getAlign(),getAlt());

JspWriterout=getJspContext().getOut();

StringBuffersb=newStringBuffer();

sb.append("<button");

//增加属性支持

for(inti=1;i<=att.attribute.size();i&#;&#;){

if(att.attribute.get(i)!=null){

sb.append("t");

sb.append(Attribute.names.get(i)&#;"=""&#;att.attribute.get(i)&#;""");

}

}

sb.append("><spanclass="icon_page">新建</span></button>");

System.out.println(sb.toString());

out.write(sb.toString());

}

}

如果很多标签都需要用到这些通用的属性,那么这样做是比较好的。

其他的标签处理父接口:

例如:TagSupport

1. import java.io.IOException;

2. import javax.servlet.jsp.JspException;

3. import javax.servlet.jsp.JspTagException;

4. import javax.servlet.jsp.tagext.TagSupport;

5. /**

6. * TagSupport与BodyTagSupport的区别:

7. * 主要看标签处理类是否要读取标签体的内容和改变标签体返回的内容,如果不需要就用TagSupport,否则就用BodyTagSupport

8. * 用TagSupport实现的标签,都可以用BodyTagSupport来实现,因为BodyTagSupport继承了TagSupport

9. */

. public class HelloWorldTag extends TagSupport {

. private static final long serialVersionUID = L;

. @Override

. public int doStartTag() throws JspException {//这个方法不用所以直接返回&#;

. return EVAL_BODY_INCLUDE;

. }

. @Override

. public int doEndTag() throws JspException {//重点在这个方法上

. try {

. pageContext.getOut().write("Hello World!");//标签的返回&#;

. } catch (IOException ex) {

. throw new JspTagException("错误");

. }

. return EVAL_PAGE;

. }

. }

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.配置标签时通过<dynamic-attribute>子元素设为true来支持动态属性。

步骤4:将这个java工程打成jar包暂存后面使用。

这个jar包中仅需要如下内容即可:

1.META-INF文件夹,下面有一个tlds的文件夹存放tld文件

2.若干标签处理类,可以把他们放置到一个文件夹中,但一定要与tld中<tag-class>路径相同。

提示:如果标签带有属性,一定要在标签处理类中为每一个属性生成其对应的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{

privatefinalStringid;

privatefinalStringencode;

privateStringtype ="";

privateStringname ="";

privateStringcharge="";

privateStringvalidate="";

publicBuilder(Stringid,Stringencode){

// TODO Auto-generatedconstructor stub

this.id=id;

this.encode=encode;

}

publicBuildertype(Stringtype){

this.type=type;

returnthis;

}

publicBuildername(Stringname){

this.name=name;

returnthis;

}

publicBuildercharge(Stringcharge){

this.charge=charge;

returnthis;

}

publicBuildervalidate(Stringvalidate){

this.validate=validate;

returnthis;

}

publicBuilderTestbuild(){

returnnewBuilderTestTag(this);

}

}

privateBuilderTestTag(Builderbuilder){

this.name=builder.name;

this.id=builder.id;

this.encode=builder.encode;

this.charge=builder.charge;

this.type=builder.type;

this.validate=builder.validate;

}

}

客户端:publicstaticvoidmain(String[]args){

BuilderTesttag=newBuilderTest.

Builder("id","encode").charge("charge").name("name").type("type").validate("validate").build();

Stringcharge=tag.charge;

Stringname=tag.name;

Stringid=tag.id;

Stringtype=tag.type;

Stringencode=tag.encode;

Stringvalidate=tag.validate;

System.out.println(charge&#;","&#;name&#;","&#;id&#;","&#;type&#;","&#;encode&#;","&#;validate);

}

当然,这里只是一种想法,并没有在标签处理类中真正实现,如果想要应用可能还需要进行改进!因为我们知道,一个标签的属性一定是要提供相应的get和set方法)

使用标签

步骤1:

创建一个插件工程,创建metadata包,在其中创建对应你的tld文件的xml描述文件,名字最好一样。

例如:box.xml

<?xml version="1.0"encoding="UTF-8"?>

<md:metadatamodel

xmlns:xsi="

xmlns:pi=" id="paletteInfos"> //palette的设置名

<valuexsi:type="pi:PaletteInfos">

<itemid="box1"/> //item表示一个标签,可以定义多个

标签,根据id在下面的entity详细 定义

</value>

</trait>

<trait id="images-base-path"> //标签库图片所在,在运行时即加载

<value>/icons/palette/box/</value>

</trait>

<trait id="display-label"> //palette中标签库的显示名称

<value>div盒子模型</value>

</trait>

<trait id="description"> //鼠标划过标签库时显示的描述信息

<value>利用div实现的盒子</value>

</trait>

<!--盒子模型1-->

<entity id="box1"type="tag"> //type是必须写成tag,id一定要与

上面的<itemid="box1"/>中的一 致

<traitid="description"> //鼠标划过相应标签显示的描述信息

<value>盒子模型1</value>

</trait>

<traitid="display-label"> //palette中标签的显示名称

<value>盒子模型1</value>

</trait>

<traitid="small-icon"> //标签的小图标

<value>box1.gif</value>

</trait>

<traitid="large-icon"> //标签的大图标

<value>box1.gif</value>

</trait>

</entity>

</md:metadatamodel>

步骤2:

在plugin.xml文件中注册刚才创建的标签库。

例如:

<!-- 配置tag (MetaDataFiles扩展点)-->

<extensionpoint="org.eclipse.jst.jsf.common.standardMetaDataFiles">

<!-- box -->

<standardMetaDataFile

location="/metadata/box.xml"

uri="box"> //uri保持一致

</standardMetaDataFile>

</extension>

步骤3:

runas 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会是将要显示到自定义标签前部的信息:<test:mytag/>。

这样,自定义的标签也就成功使用了,在服务器上跑一下看看效果吧。

Android之Broadcast与BroadcastReceiver 本文原文链接

android图片压缩终极解决方案 首先说一下论坛其他同学的压缩方法,基本上都是bitmap.compress方法,要么压缩尺寸,要么降低图片质量,这种帖子一翻一大堆。有这方面开发的同学应

Android-Universal-Image-Loader最新框架解析 Android-Universal-Image-Loader(对应版本号1.9.4为最新版)原文作者:顾学武编辑整理:快码众包目录1.个性的ImageLoader配置1.1.在哪儿配置以及如何配置2.各式

标签: 安卓通用代码

本文链接地址:https://www.jiuchutong.com/biancheng/386776.html 转载请保留说明!

上一篇:安装配置PhoneGap开发环境(安装配置jsp运行环境)

下一篇:Android之Broadcast与BroadcastReceiver

  • 怎么计算土地增值税的相关税金
  • 老项目增值税简易计税
  • 外币账户单位基本情况表
  • 财务金额表格
  • 质量扣款能按折扣计算吗
  • 其他收益属于什么类
  • 红字发票抵扣联丢了怎么办
  • 增值税专用发票和普通发票的区别
  • 通信协会费入什么科目
  • 建筑施工企业会计制度
  • 办公用品报销项目怎么写
  • 外币应收帐款汇兑损益现流附表
  • 降库存的方案
  • 汇算清缴残保金填哪里
  • 企业所得税前列支的费用
  • 二手房增值营业税
  • 吊车租赁增值税税率最新2022
  • 电子版A4黑白发票可以抵税吗?
  • 房产税缴纳时间规定
  • 客运服务费怎么开票
  • 股东贷款企业贷债务
  • 上报汇总之后怎么申报
  • 长投成本法分红分录
  • 收到投资款会计科目怎么做账
  • 大巴车票抵扣税率
  • 母公司代发工资如何处理
  • 公司年检需要什么资料
  • 增值税系统技术维护费需要勾选吗
  • 项目款申请
  • uc浏览器缓存视频删除了还占内存
  • 购入需要安装的设备的会计分录
  • 重命名电脑名称有什么用
  • php的数组函数
  • 外销收入含税吗
  • 公积金可以支付二手房首付款吗
  • gws.exe是啥
  • js在web前端中的作用
  • php date format
  • Sublime Text 4 (Build 4143) 注册方法STEP BY STEP
  • 施工单位奖金分配方案
  • 个人出租房屋要交印花税吗
  • 账户利息怎么计算
  • 织梦cms不更新了吗
  • MySQL主从数据库搭建
  • 清包工一般计税如何开票
  • 电子税务局发票作废流程
  • 工程款增值税专用发票需要写工程名称吗
  • 小企业如何核算成本费用
  • 命令行启动服务service
  • mysql 5.5 5.6 5.7
  • 研发支出资本化计入什么科目
  • 退物业费如何记帐
  • 其他业务收入的现金流量项目
  • 民营医院的发票在哪里领
  • 库存退货怎么做账
  • 固定资产为什么提折旧,有何实际意义
  • 用u盘怎么装系统win10
  • mac的虚拟机
  • windows提示滑动以关闭电脑
  • 电脑显示window
  • mac系统文件名
  • win8应用商店怎么卸载
  • excel怎么添加动态图
  • android开发手册
  • Node.js中的包管理工具是什么
  • td nowrap css nowrap使用说明于注意事项
  • python利用csv模块在对csv文件进行操作
  • vps 备份
  • bat脚本%1
  • Jquery通过ajax请求NodeJS返回json数据实例
  • unity text
  • jquery移动版
  • android studio教程入门
  • 安卓打包安装程序apk
  • 国家税务总局司长
  • 出租车票如何验真
  • 广州地税电子税票查询
  • 税务局网上开票平台app
  • 我们如何理解税收意义
  • 小微企业房产税优惠减免政策
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设