1.文件操作工具类
/**
* 以文件流的方式复制文件
* @param src 文件源目录
* @param dest 文件目的目录
* @throws IOException
*/
public static void copyFile(String src,String dest) throws IOException{
FileInputStream in=new FileInputStream(src);
File file=new File(dest);
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file);
int c;
byte buffer[]=new byte[1024];
while((c=in.read(buffer))!=-1){
for(int i=0;i<c;i++)
out.write(buffer[i]);
}
in.close();
out.close();
}
/**
* 利用PrintStream写文件
* @param src 写入文件的路径
*/
public static void PrintStreamOut(String src,String contents){
try {
FileOutputStream out=new FileOutputStream(src);
PrintStream p=new PrintStream(out);
for(int i=0;i<contents.length();i++)
p.print(contents.charAt(i));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 利用PrintStream写文件
* @param src 写入文件的路径
*/
public static void StringBufferOut(String src,String contents) throws IOException{
File file=new File(src);
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file,true);
for(int i=0;i<contents.length();i++){
StringBuffer sb=new StringBuffer();
sb.append(contents.charAt(i));
out.write(sb.toString().getBytes("utf-8"));
}
out.close();
}
/**
* 文件重命名
* @param path 文件目录
* @param oldname 原来的文件名
* @param newname 新文件名
* @param num 已存在该文件名
*/
public static void renameFile(String path,String oldname,String newname,int num,String suffix){
if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
File oldfile=new File(path+"/"+oldname);
File newfile = null;
String temp = newname;
if(num==0){
newname = newname+suffix;
newfile=new File(path+"/"+newname);
}else{
newname = newname+num+suffix;
newfile=new File(path+"/"+newname);
}
if(newfile.exists()){//若在该目录下已经有一个文件和新文件名相同,则命名为newname1.2.3...
num++;
renameFile(path,oldname,temp,num,suffix);
}else{
oldfile.renameTo(newfile);
}
}
}
/**
* 转移文件目录
* @param filename 文件名
* @param oldpath 旧目录
* @param newpath 新目录
* @param cover 若新目录下存在和转移文件具有相同文件名的文件时,是否覆盖新目录下文件,cover=true将会覆盖原文件,否则不操作
*/
public static void changeDirectory(String filename,String oldpath,String newpath,boolean cover){
if(!oldpath.equals(newpath)){
File oldfile=new File(oldpath+"/"+filename);
File newfile=new File(newpath+"/"+filename);
if(newfile.exists()){//若在待转移目录下,已经存在待转移文件
if(cover){//覆盖
newfile.delete();
oldfile.renameTo(newfile);
}else
System.out.println("在新目录下已经存在:"+filename);
}
else{
oldfile.renameTo(newfile);
}
}
}
/**
* @author LiZhen
* @param strFile
* @throws Exception
*/
public static void UnZip(String strFile) throws Exception {
// 输出文件夹
String baseDir = "d:\";
ZipFile zFile = new ZipFile(strFile);
System.out.println(zFile.getName());
Enumeration en = zFile.entries();
ZipEntry entry = null;
while (en.hasMoreElements()) {
// 得到其中一项ZipEntry
entry = (ZipEntry) en.nextElement();
// 如果是文件夹则不处理
if (entry.isDirectory()) {
System.out.println("Dir: " + entry.getName() + " skipped..");
} else {
// 如果是文件则写到输出目录
copyFile(zFile, baseDir, entry);
}
}
zFile.close();
}
private static void copyFile(ZipFile source, String baseDir, ZipEntry entry)
throws Exception {
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
// 是否需要创建目录
mkdirs(baseDir, entry.getName());
// 建立输出流
OutputStream os = new BufferedOutputStream(new FileOutputStream(
new File(baseDir, entry.getName())));
// 取得对应ZipEntry的输入流
InputStream is = new BufferedInputStream(source.getInputStream(entry));
int readLen = 0;
byte[] buf = new byte[1024];
// 复制文件
System.out.println("Extracting: " + entry.getName() + "t"
+ entry.getSize() + "t" + entry.getCompressedSize());
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
System.out.println("Extracted: " + entry.getName());
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private static void mkdirs(String baseDir, String relativeFileName) {
String[] dirs = relativeFileName.split("/");
File ret = new File(baseDir);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {
ret.mkdirs();
}
}
2.Bitmap与DrawAble与byte[]与InputStream之间的转换工具类
package com.soai.imdemo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
/**
* Bitmap与DrawAble与byte[]与InputStream之间的转换工具类
* @author Administrator
*
*/
public class FormatTools {
private static FormatTools tools = new FormatTools();
public static FormatTools getInstance() {
if (tools == null) {
tools = new FormatTools();
return tools;
}
return tools;
}
// 将byte[]转换成InputStream
public InputStream Byte2InputStream(byte[] b) {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
return bais;
}
// 将InputStream转换成byte[]
public byte[] InputStream2Bytes(InputStream is) {
String str = "";
byte[] readByte = new byte[1024];
int readCount = -1;
try {
while ((readCount = is.read(readByte, 0, 1024)) != -1) {
str += new String(readByte).trim();
}
return str.getBytes();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 将Bitmap转换成InputStream
public InputStream Bitmap2InputStream(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
// 将Bitmap转换成InputStream
public InputStream Bitmap2InputStream(Bitmap bm, int quality) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, quality, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
// 将InputStream转换成Bitmap
public Bitmap InputStream2Bitmap(InputStream is) {
return BitmapFactory.decodeStream(is);
}
// Drawable转换成InputStream
public InputStream Drawable2InputStream(Drawable d) {
Bitmap bitmap = this.drawable2Bitmap(d);
return this.Bitmap2InputStream(bitmap);
}
// InputStream转换成Drawable
public Drawable InputStream2Drawable(InputStream is) {
Bitmap bitmap = this.InputStream2Bitmap(is);
return this.bitmap2Drawable(bitmap);
}
// Drawable转换成byte[]
public byte[] Drawable2Bytes(Drawable d) {
Bitmap bitmap = this.drawable2Bitmap(d);
return this.Bitmap2Bytes(bitmap);
}
// byte[]转换成Drawable
public Drawable Bytes2Drawable(byte[] b) {
Bitmap bitmap = this.Bytes2Bitmap(b);
return this.bitmap2Drawable(bitmap);
}
// Bitmap转换成byte[]
public byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
// byte[]转换成Bitmap
public Bitmap Bytes2Bitmap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
return null;
}
// Drawable转换成Bitmap
public Bitmap drawable2Bitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
// Bitmap转换成Drawable
public Drawable bitmap2Drawable(Bitmap bitmap) {
BitmapDrawable bd = new BitmapDrawable(bitmap);
Drawable d = (Drawable) bd;
return d;
}
}
3.其它常用工具类
一. 检查网络是否可用.
ConnectionUtil.java
-
import android.app.AlertDialog;
-
import android.content.Context;
-
import android.content.DialogInterface;
-
import android.net.ConnectivityManager;
-
import android.net.NetworkInfo;
-
-
-
public class ConnectionUtil {
-
-
-
-
-
-
-
public static boolean isNetworkAvailable(Context context) {
-
ConnectivityManager connectivity = (ConnectivityManager) context
-
.getSystemService(Context.CONNECTIVITY_SERVICE);
-
-
if (connectivity == null) {
-
-
return false;
-
} else {
-
NetworkInfo[] info = connectivity.getAllNetworkInfo();
-
-
if (info != null) {
-
-
for (int i = 0; i < info.length; i++) {
-
-
if (info[i].isConnected()) {
-
-
return true;
-
}
-
}
-
}
-
}
-
return false;
-
}
-
-
public static void httpTest(final Context ctx,String title,String msg) {
-
if (!isNetworkAvailable(ctx)) {
-
AlertDialog.Builder builders = new AlertDialog.Builder(ctx);
-
builders.setTitle(title);
-
builders.setMessage(msg);
-
builders.setPositiveButton(android.R.string.ok,
-
new DialogInterface.OnClickListener() {
-
public void onClick(DialogInterface dialog, int which) {
-
-
}
-
});
-
AlertDialog alert = builders.create();
-
alert.show();
-
}
-
}
-
}
二.读取流文件.
FileStreamTool.java
-
import java.io.ByteArrayOutputStream;
-
import java.io.File;
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.io.PushbackInputStream;
-
-
-
public class FileStreamTool {
-
-
-
public static void save(File file, byte[] data) throws Exception {
-
FileOutputStream outStream = new FileOutputStream(file);
-
outStream.write(data);
-
outStream.close();
-
}
-
-
public static String readLine(PushbackInputStream in) throws IOException {
-
char buf[] = new char[128];
-
int room = buf.length;
-
int offset = 0;
-
int c;
-
loop: while (true) {
-
switch (c = in.read()) {
-
case -1:
-
case '\n':
-
break loop;
-
case '\r':
-
int c2 = in.read();
-
if ((c2 != '\n') && (c2 != -1)) in.unread(c2);
-
break loop;
-
default:
-
if (--room < 0) {
-
char[] lineBuffer = buf;
-
buf = new char[offset + 128];
-
room = buf.length - offset - 1;
-
System.arraycopy(lineBuffer, 0, buf, 0, offset);
-
-
}
-
buf[offset++] = (char) c;
-
break;
-
}
-
}
-
if ((c == -1) && (offset == 0)) return null;
-
return String.copyValueOf(buf, 0, offset);
-
}
-
-
-
-
-
-
-
-
public static byte[] readStream(InputStream inStream) throws Exception{
-
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
-
byte[] buffer = new byte[1024];
-
int len = -1;
-
while( (len=inStream.read(buffer)) != -1){
-
outSteam.write(buffer, 0, len);
-
}
-
outSteam.close();
-
inStream.close();
-
return outSteam.toByteArray();
-
}
-
}
三.文件断点续传.
MainActivity.java
-
import java.io.File;
-
import java.io.OutputStream;
-
import java.io.PushbackInputStream;
-
import java.io.RandomAccessFile;
-
import java.net.Socket;
-
import cn.itcast.service.UploadLogService;
-
import cn.itcast.utils.StreamTool;
-
import android.app.Activity;
-
import android.os.Bundle;
-
import android.os.Environment;
-
import android.os.Handler;
-
import android.os.Message;
-
import android.view.View;
-
import android.widget.Button;
-
import android.widget.EditText;
-
import android.widget.ProgressBar;
-
import android.widget.TextView;
-
import android.widget.Toast;
-
-
-
public class MainActivity extends Activity {
-
private EditText filenameText;
-
private TextView resultView;
-
private ProgressBar uploadbar;
-
private UploadLogService service;
-
private Handler handler = new Handler(){
-
@Override
-
public void handleMessage(Message msg) {
-
uploadbar.setProgress(msg.getData().getInt("length"));
-
float num = (float)uploadbar.getProgress() / (float)uploadbar.getMax();
-
int result = (int)(num * 100);
-
resultView.setText(result + "%");
-
if(uploadbar.getProgress() == uploadbar.getMax()){
-
Toast.makeText(MainActivity.this, R.string.success, 1).show();
-
}
-
}
-
};
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
-
service = new UploadLogService(this);
-
filenameText = (EditText)findViewById(R.id.filename);
-
resultView = (TextView)findViewById(R.id.result);
-
uploadbar = (ProgressBar)findViewById(R.id.uploadbar);
-
Button button = (Button)findViewById(R.id.button);
-
button.setOnClickListener(new View.OnClickListener() {
-
-
public void onClick(View v) {
-
String filename = filenameText.getText().toString();
-
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
-
File file = new File(Environment.getExternalStorageDirectory(), filename);
-
if(file.exists()){
-
uploadbar.setMax((int)file.length());
-
uploadFile(file);
-
}else{
-
Toast.makeText(MainActivity.this, R.string.notexsit, 1).show();
-
}
-
}else{
-
Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();
-
}
-
}
-
});
-
}
-
-
-
private void uploadFile(final File file) {
-
new Thread(new Runnable() {
-
-
public void run() {
-
try {
-
String sourceid = service.getBindId(file);
-
Socket socket = new Socket("192.168.1.100", 7878);
-
OutputStream outStream = socket.getOutputStream();
-
String head = "Content-Length="+ file.length() + ";filename="+ file.getName()
-
+ ";sourceid="+(sourceid!=null ? sourceid : "")+"\r\n";
-
outStream.write(head.getBytes());
-
-
PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
-
-
String response = StreamTool.readLine(inStream);
-
String[] items = response.split(";");
-
String responseSourceid = items[0].substring(items[0].indexOf("=")+1);
-
String position = items[1].substring(items[1].indexOf("=")+1);
-
if(sourceid==null){
-
service.save(responseSourceid, file);
-
}
-
RandomAccessFile fileOutStream = new RandomAccessFile(file, "r");
-
fileOutStream.seek(Integer.valueOf(position));
-
byte[] buffer = new byte[1024];
-
int len = -1;
-
int length = Integer.valueOf(position);
-
while( (len = fileOutStream.read(buffer)) != -1){
-
outStream.write(buffer, 0, len);
-
length += len;
-
Message msg = new Message();
-
msg.getData().putInt("length", length);
-
handler.sendMessage(msg);
-
}
-
if(length == file.length()) service.delete(file);
-
fileOutStream.close();
-
outStream.close();
-
inStream.close();
-
socket.close();
-
} catch (Exception e) {
-
Toast.makeText(MainActivity.this, R.string.error, 1).show();
-
}
-
}
-
}).start();
-
}
-
}
DBOpenHelper.java
-
import android.content.Context;
-
import android.database.sqlite.SQLiteDatabase;
-
import android.database.sqlite.SQLiteOpenHelper;
-
-
-
public class DBOpenHelper extends SQLiteOpenHelper {
-
-
-
public DBOpenHelper(Context context) {
-
super(context, "itcast.db", null, 1);
-
}
-
-
@Override
-
public void onCreate(SQLiteDatabase db) {
-
db.execSQL("CREATE TABLE IF NOT EXISTS uploadlog (_id integer primary key autoincrement, path varchar(20), sourceid varchar(20))");
-
}
-
-
@Override
-
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
-
}
-
-
}
UpLoadLogService.java
-
import java.io.File;
-
import android.content.Context;
-
import android.database.Cursor;
-
import android.database.sqlite.SQLiteDatabase;
-
-
-
public class UploadLogService {
-
private DBOpenHelper dbOpenHelper;
-
-
public UploadLogService(Context context){
-
dbOpenHelper = new DBOpenHelper(context);
-
}
-
-
public String getBindId(File file){
-
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
-
Cursor cursor = db.rawQuery("select sourceid from uploadlog where path=?", new String[]{file.getAbsolutePath()});
-
if(cursor.moveToFirst()){
-
return cursor.getString(0);
-
}
-
return null;
-
}
-
-
public void save(String sourceid, File file){
-
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
-
db.execSQL("insert into uploadlog(path,sourceid) values(?,?)",
-
new Object[]{file.getAbsolutePath(), sourceid});
-
}
-
-
public void delete(File file){
-
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
-
db.execSQL("delete from uploadlog where path=?", new Object[]{file.getAbsolutePath()});
-
}
-
}
四.多线程断点续传.
MainActivity.java
-
import java.io.File;
-
import cn.itcast.net.download.DownloadProgressListener;
-
import cn.itcast.net.download.FileDownloader;
-
import android.app.Activity;
-
import android.os.Bundle;
-
import android.os.Environment;
-
import android.os.Handler;
-
import android.os.Message;
-
import android.view.View;
-
import android.widget.Button;
-
import android.widget.EditText;
-
import android.widget.ProgressBar;
-
import android.widget.TextView;
-
import android.widget.Toast;
-
-
-
public class MainActivity extends Activity {
-
private EditText pathText;
-
private TextView resultView;
-
private Button downloadButton;
-
private Button stopbutton;
-
private ProgressBar progressBar;
-
-
private Handler handler = new UIHander();
-
-
private final class UIHander extends Handler{
-
public void handleMessage(Message msg) {
-
switch (msg.what) {
-
case 1:
-
int size = msg.getData().getInt("size");
-
progressBar.setProgress(size);
-
float num = (float)progressBar.getProgress() / (float)progressBar.getMax();
-
int result = (int)(num * 100);
-
resultView.setText(result+ "%");
-
if(progressBar.getProgress() == progressBar.getMax()){
-
Toast.makeText(getApplicationContext(), R.string.success, 1).show();
-
}
-
break;
-
-
-
case -1:
-
Toast.makeText(getApplicationContext(), R.string.error, 1).show();
-
break;
-
}
-
}
-
}
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
-
pathText = (EditText) this.findViewById(R.id.path);
-
resultView = (TextView) this.findViewById(R.id.resultView);
-
downloadButton = (Button) this.findViewById(R.id.downloadbutton);
-
stopbutton = (Button) this.findViewById(R.id.stopbutton);
-
progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
-
ButtonClickListener listener = new ButtonClickListener();
-
downloadButton.setOnClickListener(listener);
-
stopbutton.setOnClickListener(listener);
-
}
-
-
private final class ButtonClickListener implements View.OnClickListener{
-
public void onClick(View v) {
-
switch (v.getId()) {
-
case R.id.downloadbutton:
-
String path = pathText.getText().toString();
-
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
-
File saveDir = Environment.getExternalStorageDirectory();
-
download(path, saveDir);
-
}else{
-
Toast.makeText(getApplicationContext(), R.string.sdcarderror, 1).show();
-
}
-
downloadButton.setEnabled(false);
-
stopbutton.setEnabled(true);
-
break;
-
-
-
case R.id.stopbutton:
-
exit();
-
downloadButton.setEnabled(true);
-
stopbutton.setEnabled(false);
-
break;
-
}
-
}
-
-
-
-
-
-
-
private DownloadTask task;
-
-
-
-
public void exit(){
-
if(task!=null) task.exit();
-
}
-
private void download(String path, File saveDir) {
-
task = new DownloadTask(path, saveDir);
-
new Thread(task).start();
-
}
-
-
-
-
-
-
-
private final class DownloadTask implements Runnable{
-
private String path;
-
private File saveDir;
-
private FileDownloader loader;
-
public DownloadTask(String path, File saveDir) {
-
this.path = path;
-
this.saveDir = saveDir;
-
}
-
-
-
-
public void exit(){
-
if(loader!=null) loader.exit();
-
}
-
-
public void run() {
-
try {
-
loader = new FileDownloader(getApplicationContext(), path, saveDir, 3);
-
progressBar.setMax(loader.getFileSize());
-
loader.download(new DownloadProgressListener() {
-
public void onDownloadSize(int size) {
-
Message msg = new Message();
-
msg.what = 1;
-
msg.getData().putInt("size", size);
-
handler.sendMessage(msg);
-
}
-
});
-
} catch (Exception e) {
-
e.printStackTrace();
-
handler.sendMessage(handler.obtainMessage(-1));
-
}
-
}
-
}
-
}
-
-
-
}
DBOpenHelper.java
-
import android.content.Context;
-
import android.database.sqlite.SQLiteDatabase;
-
import android.database.sqlite.SQLiteOpenHelper;
-
-
public class DBOpenHelper extends SQLiteOpenHelper {
-
private static final String DBNAME = "itcast.db";
-
private static final int VERSION = 1;
-
-
public DBOpenHelper(Context context) {
-
super(context, DBNAME, null, VERSION);
-
}
-
-
@Override
-
public void onCreate(SQLiteDatabase db) {
-
db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength INTEGER)");
-
}
-
-
@Override
-
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
db.execSQL("DROP TABLE IF EXISTS filedownlog");
-
onCreate(db);
-
}
-
}
FileService.java
-
import java.util.HashMap;
-
import java.util.Map;
-
import android.content.Context;
-
import android.database.Cursor;
-
import android.database.sqlite.SQLiteDatabase;
-
-
-
-
-
public class FileService {
-
private DBOpenHelper openHelper;
-
-
-
public FileService(Context context) {
-
openHelper = new DBOpenHelper(context);
-
}
-
-
-
-
-
-
public Map<Integer, Integer> getData(String path){
-
SQLiteDatabase db = openHelper.getReadableDatabase();
-
Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[]{path});
-
Map<Integer, Integer> data = new HashMap<Integer, Integer>();
-
while(cursor.moveToNext()){
-
data.put(cursor.getInt(0), cursor.getInt(1));
-
}
-
cursor.close();
-
db.close();
-
return data;
-
}
-
-
-
-
-
-
public void save(String path, Map<Integer, Integer> map){
-
SQLiteDatabase db = openHelper.getWritableDatabase();
-
db.beginTransaction();
-
try{
-
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
-
db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",
-
new Object[]{path, entry.getKey(), entry.getValue()});
-
}
-
db.setTransactionSuccessful();
-
}finally{
-
db.endTransaction();
-
}
-
db.close();
-
}
-
-
-
-
-
-
public void update(String path, int threadId, int pos){
-
SQLiteDatabase db = openHelper.getWritableDatabase();
-
db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?",
-
new Object[]{pos, path, threadId});
-
db.close();
-
}
-
-
-
-
-
public void delete(String path){
-
SQLiteDatabase db = openHelper.getWritableDatabase();
-
db.execSQL("delete from filedownlog where downpath=?", new Object[]{path});
-
db.close();
-
}
-
-
}
DownloadProgressListener.java
-
public interface DownloadProgressListener {
-
public void onDownloadSize(int size);
-
}
DownLoadThread.java
-
import java.io.File;
-
import java.io.InputStream;
-
import java.io.RandomAccessFile;
-
import java.net.HttpURLConnection;
-
import java.net.URL;
-
import android.util.Log;
-
-
public class DownloadThread extends Thread {
-
private static final String TAG = "DownloadThread";
-
private File saveFile;
-
private URL downUrl;
-
private int block;
-
-
private int threadId = -1;
-
-
private int downLength;
-
private boolean finish = false;
-
private FileDownloader downloader;
-
-
public DownloadThread(FileDownloader downloader, URL downUrl, File saveFile, int block, int downLength, int threadId) {
-
this.downUrl = downUrl;
-
this.saveFile = saveFile;
-
this.block = block;
-
this.downloader = downloader;
-
this.threadId = threadId;
-
this.downLength = downLength;
-
}
-
-
@Override
-
public void run() {
-
if(downLength < block){
-
try {
-
HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();
-
http.setConnectTimeout(5 * 1000);
-
http.setRequestMethod("GET");
-
http.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
-
http.setRequestProperty("Accept-Language", "zh-CN");
-
http.setRequestProperty("Referer", downUrl.toString());
-
http.setRequestProperty("Charset", "UTF-8");
-
int startPos = block * (threadId - 1) + downLength;
-
int endPos = block * threadId -1;
-
http.setRequestProperty("Range", "bytes=" + startPos + "-"+ endPos);
-
http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
-
http.setRequestProperty("Connection", "Keep-Alive");
-
-
InputStream inStream = http.getInputStream();
-
byte[] buffer = new byte[1024];
-
int offset = 0;
-
print("Thread " + this.threadId + " start download from position "+ startPos);
-
RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");
-
threadfile.seek(startPos);
-
while (!downloader.getExit() && (offset = inStream.read(buffer, 0, 1024)) != -1) {
-
threadfile.write(buffer, 0, offset);
-
downLength += offset;
-
downloader.update(this.threadId, downLength);
-
downloader.append(offset);
-
}
-
threadfile.close();
-
inStream.close();
-
print("Thread " + this.threadId + " download finish");
-
this.finish = true;
-
} catch (Exception e) {
-
this.downLength = -1;
-
print("Thread "+ this.threadId+ ":"+ e);
-
}
-
}
-
}
-
private static void print(String msg){
-
Log.i(TAG, msg);
-
}
-
/**
-
* 下载是否完成
-
* @return
-
*/
-
public boolean isFinish() {
-
return finish;
-
}
-
-
-
-
-
public long getDownLength() {
-
return downLength;
-
}
-
}
FileDownloader.java
-
import java.io.File;
-
import java.io.RandomAccessFile;
-
import java.net.HttpURLConnection;
-
import java.net.URL;
-
import java.util.LinkedHashMap;
-
import java.util.Map;
-
import java.util.UUID;
-
import java.util.concurrent.ConcurrentHashMap;
-
import java.util.regex.Matcher;
-
import java.util.regex.Pattern;
-
import cn.itcast.service.FileService;
-
-
-
import android.content.Context;
-
import android.util.Log;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public class FileDownloader {
-
private static final String TAG = "FileDownloader";
-
private Context context;
-
private FileService fileService;
-
-
private boolean exit;
-
-
private int downloadSize = 0;
-
-
private int fileSize = 0;
-
-
private DownloadThread[] threads;
-
-
private File saveFile;
-
-
private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();
-
-
private int block;
-
-
private String downloadUrl;
-
-
-
-
public int getThreadSize() {
-
return threads.length;
-
}
-
-
-
-
public void exit(){
-
this.exit = true;
-
}
-
public boolean getExit(){
-
return this.exit;
-
}
-
-
-
-
-
public int getFileSize() {
-
return fileSize;
-
}
-
-
-
-
-
protected synchronized void append(int size) {
-
downloadSize += size;
-
}
-
-
-
-
-
-
protected synchronized void update(int threadId, int pos) {
-
this.data.put(threadId, pos);
-
this.fileService.update(this.downloadUrl, threadId, pos);
-
}
-
-
-
-
-
-
-
public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum) {
-
try {
-
this.context = context;
-
this.downloadUrl = downloadUrl;
-
fileService = new FileService(this.context);
-
URL url = new URL(this.downloadUrl);
-
if(!fileSaveDir.exists()) fileSaveDir.mkdirs();
-
this.threads = new DownloadThread[threadNum];
-
-
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
conn.setConnectTimeout(5*1000);
-
conn.setRequestMethod("GET");
-
conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
-
conn.setRequestProperty("Accept-Language", "zh-CN");
-
conn.setRequestProperty("Referer", downloadUrl);
-
conn.setRequestProperty("Charset", "UTF-8");
-
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
-
conn.setRequestProperty("Connection", "Keep-Alive");
-
conn.connect();
-
printResponseHeader(conn);
-
if (conn.getResponseCode()==200) {
-
this.fileSize = conn.getContentLength();
-
if (this.fileSize <= 0) throw new RuntimeException("Unkown file size ");
-
-
String filename = getFileName(conn);
-
this.saveFile = new File(fileSaveDir, filename);
-
Map<Integer, Integer> logdata = fileService.getData(downloadUrl);
-
if(logdata.size()>0){
-
for(Map.Entry<Integer, Integer> entry : logdata.entrySet())
-
data.put(entry.getKey(), entry.getValue());
-
}
-
if(this.data.size()==this.threads.length){
-
for (int i = 0; i < this.threads.length; i++) {
-
this.downloadSize += this.data.get(i+1);
-
}
-
print("已经下载的长度"+ this.downloadSize);
-
}
-
-
this.block = (this.fileSize % this.threads.length)==0? this.fileSize / this.threads.length : this.fileSize / this.threads.length + 1;
-
}else{
-
throw new RuntimeException("server no response ");
-
}
-
} catch (Exception e) {
-
print(e.toString());
-
throw new RuntimeException("don't connection this url");
-
}
-
}
-
/**
-
* 获取文件名
-
*/
-
private String getFileName(HttpURLConnection conn) {
-
String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);
-
if(filename==null || "".equals(filename.trim())){
-
for (int i = 0;; i++) {
-
String mine = conn.getHeaderField(i);
-
if (mine == null) break;
-
if("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())){
-
Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
-
if(m.find()) return m.group(1);
-
}
-
}
-
filename = UUID.randomUUID()+ ".tmp";
-
}
-
return filename;
-
}
-
-
-
-
-
-
-
-
public int download(DownloadProgressListener listener) throws Exception{
-
try {
-
RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");
-
if(this.fileSize>0) randOut.setLength(this.fileSize);
-
randOut.close();
-
URL url = new URL(this.downloadUrl);
-
if(this.data.size() != this.threads.length){
-
this.data.clear();
-
for (int i = 0; i < this.threads.length; i++) {
-
this.data.put(i+1, 0);
-
}
-
this.downloadSize = 0;
-
}
-
for (int i = 0; i < this.threads.length; i++) {
-
int downLength = this.data.get(i+1);
-
if(downLength < this.block && this.downloadSize<this.fileSize){
-
-
this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);
-
this.threads[i].setPriority(7);
-
this.threads[i].start();
-
}else{
-
this.threads[i] = null;
-
}
-
}
-
fileService.delete(this.downloadUrl);
-
fileService.save(this.downloadUrl, this.data);
-
boolean notFinish = true;
-
while (notFinish) {
-
Thread.sleep(900);
-
notFinish = false;
-
for (int i = 0; i < this.threads.length; i++){
-
if (this.threads[i] != null && !this.threads[i].isFinish()) {
-
notFinish = true;
-
if(this.threads[i].getDownLength() == -1){
-
this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);
-
this.threads[i].setPriority(7);
-
this.threads[i].start();
-
}
-
}
-
}
-
if(listener!=null) listener.onDownloadSize(this.downloadSize);
-
}
-
if(downloadSize == this.fileSize) fileService.delete(this.downloadUrl);
-
} catch (Exception e) {
-
print(e.toString());
-
throw new Exception("file download error");
-
}
-
return this.downloadSize;
-
}
-
-
-
-
-
-
public static Map<String, String> getHttpResponseHeader(HttpURLConnection http) {
-
Map<String, String> header = new LinkedHashMap<String, String>();
-
for (int i = 0;; i++) {
-
String mine = http.getHeaderField(i);
-
if (mine == null) break;
-
header.put(http.getHeaderFieldKey(i), mine);
-
}
-
return header;
-
}
-
-
-
-
-
public static void printResponseHeader(HttpURLConnection http){
-
Map<String, String> header = getHttpResponseHeader(http);
-
for(Map.Entry<String, String> entry : header.entrySet()){
-
String key = entry.getKey()!=null ? entry.getKey()+ ":" : "";
-
print(key+ entry.getValue());
-
}
-
}
-
-
-
private static void print(String msg){
-
Log.i(TAG, msg);
-
}
-
}
4.日期转换工具类
package com.mbl.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class FormatDateTime {
/**
* 日期类操作工具
*/
public static String formatDateTime(String ymd){
//格式化当前时间
java.text.SimpleDateFormat isNow = new java.text.SimpleDateFormat(ymd);
String now = isNow.format(new java.util.Date());
return now;
}
public static String formatDateTime(String ymd, String datetime){
//格式化当前时间
java.text.SimpleDateFormat isNow = new java.text.SimpleDateFormat(ymd);
String now = "";
try{
isNow.format(datetime);
}catch(Exception e){
e.printStackTrace();
}
return now;
}
/* 比较当前日期和指定日期 return boolean
* 如果当前日期在指定日期之后返回true否则返回flase
*/
public static boolean dateCompare(String str){
boolean bea = false;
SimpleDateFormat sdf_d = new SimpleDateFormat("yyyy-MM-dd");
String isDate = sdf_d.format(new java.util.Date());
java.util.Date date1;
java.util.Date date0;
try {
date1 = sdf_d.parse(str);
date0= sdf_d.parse(isDate);
if(date0.after(date1)){
bea = true;
}
} catch (ParseException e) {
bea = false;
}
return bea;
}
/*
* 比较当前月份和指定月份
* 如果当前月份在指定月份之后返回true否则返回flase
*/
public static boolean monthCompare(String str){
boolean bea = false;
SimpleDateFormat sdf_m = new SimpleDateFormat("yyyy-MM");
String isMonth = sdf_m.format(new java.util.Date());
java.util.Date date1;
java.util.Date date0;
try {
date1 = sdf_m.parse(str);
date0= sdf_m.parse(isMonth);
if(date0.after(date1)){
bea = true;
}
} catch (ParseException e) {
bea = false;
}
return bea;
}
/* 比较当前日期和指定日期 return boolean
* 如果当前日期在指定日期之后返回true否则返回flase
*/
public static boolean secondCompare(String str){
boolean bea = false;
SimpleDateFormat sdf_d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String isDate = sdf_d.format(new java.util.Date());
java.util.Date date1;
java.util.Date date0;
try {
date1 = sdf_d.parse(str);
date0= sdf_d.parse(isDate);
if(date0.after(date1)){
bea = true;
}
} catch (ParseException e) {
bea = false;
}
return bea;
}
/**
* 比较指定两日期如果str1晚于str2则return true;
* @param str1
* @param str2
* @return
*/
public static boolean secondCompare(String str1, String str2){
boolean bea = false;
SimpleDateFormat sdf_d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date1;
java.util.Date date0;
try {
date1 = sdf_d.parse(str1);
date0= sdf_d.parse(str2);
if(date0.after(date1)){
bea = true;
}
} catch (ParseException e) {
bea = false;
}
return bea;
}
/**
* 设置间隔数后返回时间
* @param type 间隔类型 秒或者天
* @param 间隔数字 比如1秒或者一天
* @return
*/
public static String dateAdd(String type, int i){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = formatDateTime("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance(); // 当时的日期和时间
if(type.equals("s")){
int s = c.get(Calendar.SECOND);
s = s + i;
c.set(Calendar.SECOND, s);
str = df.format(c.getTime());
}
else if(type.equals("d")){
int d = c.get(Calendar.DAY_OF_MONTH); // 取出“日”数
d = d + i;
c.set(Calendar.DAY_OF_MONTH, d); // 将“日”数设置回去
str = df.format(c.getTime());
}
return str;
}
/* test
public static void main(String args[]){
String s1 = FormatDateTime.formatDateTime("yyyy-MM-dd","2005-10-12");
System.out.println(s1);
}
*/
}
5.Android工具类——处理网络、内存、屏幕等操作
public class CommonUtil {
public static boolean hasSDCard() {
String status = Environment.getExternalStorageState();
return status.equals(Environment.MEDIA_MOUNTED);
}
/**
* 获取最大内存
*
* @return
*/
public static long getMaxMemory() {
return Runtime.getRuntime().maxMemory() / 1024;
}
/**
* 检查网络
*
* @param context
* @return
*/
public static boolean checkNetState(Context context) {
boolean netstate = false;
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
netstate = true;
break;
}
}
}
}
return netstate;
}
public static void showToast(Context context, String tip) {
Toast.makeText(context, tip, Toast.LENGTH_SHORT).show();
}
public static DisplayMetrics metric = new DisplayMetrics();
/**
* 得到屏幕高度
*
* @param context
* @return
*/
public static int getScreenHeight(Activity context) {
context.getWindowManager().getDefaultDisplay().getMetrics(metric);
return metric.heightPixels;
}
/**
* 得到屏幕宽度
*
* @param context
* @return
*/
public static int getScreenWidth(Activity context) {
context.getWindowManager().getDefaultDisplay().getMetrics(metric);
return metric.widthPixels;
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 查询手机内非系统应用
*
* @param context
* @return
*/
public static List<PackageInfo> getAllApps(Context context) {
List<PackageInfo> apps = new ArrayList<PackageInfo>();
PackageManager pManager = context.getPackageManager();
// 获取手机内所有应用
List<PackageInfo> paklist = pManager.getInstalledPackages(0);
for (int i = 0; i < paklist.size(); i++) {
PackageInfo pak = (PackageInfo) paklist.get(i);
// 判断是否为非系统预装的应用程序
if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
// customs applications
apps.add(pak);
}
}
return apps;
}
public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}
/**
* 获取版本号和版本次数
*
* @param context
* @return
*/
public static String getVersionCode(Context context, int type) {
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
if (type == 1) {
return String.valueOf(pi.versionCode);
} else {
return pi.versionName;
}
} catch (NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
// 通过Service的类名来判断是否启动某个服务
public static boolean messageServiceIsStart(
List<ActivityManager.RunningServiceInfo> mServiceList,
String className) {
for (int i = 0; i < mServiceList.size(); i++) {
if (className.equals(mServiceList.get(i).service.getClassName())) {
return true;
}
}
return false;
}
}
6.常用工具类库
目前包括HttpUtils、DownloadManagerPro、ShellUtils、PackageUtils、PreferencesUtils、JSONUtils、FileUtils、ResourceUtils、StringUtils、ParcelUtils、RandomUtils、ArrayUtils、ImageUtils、ListUtils、MapUtils、ObjectUtils、SerializeUtils、SystemUtils、TimeUtils。
The English version of this article see:Android Common Utils
所有代码都在TrineaAndroidCommon@Github中,欢迎Star或Fork^_*,除这些工具类外此项目还包括缓存、下拉ListView等。详细接口介绍可见TrineaAndroidCommon API Guide。
具体使用:可直接引入TrineaAndroidCommon作为你项目的library(如何拉取代码及添加公共库),或是自己抽取其中的部分使用。
1、HttpUtils
Http网络工具类,主要包括httpGet、httpPost以及http参数相关方法,以httpGet为例:
static HttpResponse httpGet(HttpRequest request)
static HttpResponse httpGet(java.lang.String httpUrl)
static String httpGetString(String httpUrl)
包含以上三个方法,默认使用gzip压缩,使用bufferedReader提高读取速度。
HttpRequest中可以设置url、timeout、userAgent等其他http参数
HttpResponse中可以获取返回内容、http响应码、http过期时间(Cache-Control的max-age和expires)等
前两个方法可以进行高级参数设置及丰富内容返回,第三个方法可以简单的传入url获取返回内容,httpPost类似。更详细的设置可以直接使用HttpURLConnection或apache的HttpClient。
源码可见HttpUtils.java,更多方法及更详细参数介绍可见HttpUtils Api Guide。
2、DownloadManagerPro
Android系统下载管理DownloadManager增强方法,可用于包括获取下载相关信息,如:
getStatusById(long) 得到下载状态
getDownloadBytes(long) 得到下载进度信息
getBytesAndStatus(long) 得到下载进度信息和状态
getFileName(long) 得到下载文件路径
getUri(long) 得到下载uri
getReason(long) 得到下载失败或暂停原因
getPausedReason(long) 得到下载暂停原因
getErrorCode(long) 得到下载错误码
源码可见DownloadManagerPro.java,更多方法及更详细参数介绍可见DownloadManagerPro Api Guide。关于Android DownManager使用可见DownManager Demo。
3、ShellUtils
Android Shell工具类,可用于检查系统root权限,并在shell或root用户下执行shell命令。如:
checkRootPermission() 检查root权限
execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) shell环境执行命令,第二个参数表示是否root权限执行
execCommand(String command, boolean isRoot) shell环境执行命令
源码可见ShellUtils.java,更多方法及更详细参数介绍可见ShellUtils Api Guide。关于静默安装可见apk-root权限静默安装。
4、PackageUtils
Android包相关工具类,可用于(root)安装应用、(root)卸载应用、判断是否系统应用等,如:
install(Context, String) 安装应用,如果是系统应用或已经root,则静默安装,否则一般安装
uninstall(Context, String) 卸载应用,如果是系统应用或已经root,则静默卸载,否则一般卸载
isSystemApplication(Context, String) 判断应用是否为系统应用
源码可见PackageUtils.java,更多方法及更详细参数介绍可见ShellUtils Api Guide。关于静默安装可见apk-root权限静默安装。
5、PreferencesUtils
Android SharedPreferences相关工具类,可用于方便的向SharedPreferences中读取和写入相关类型数据,如:
putString(Context, String, String) 保存string类型数据
putInt(Context, String, int) 保存int类型数据
getString(Context, String) 获取string类型数据
getInt(Context, String) 获取int类型数据
可通过修改PREFERENCE_NAME变量修改preference name
源码可见PreferencesUtils.java,更多方法及更详细参数介绍可见PreferencesUtils Api Guide。
6、JSONUtils
JSONUtils工具类,可用于方便的向Json中读取和写入相关类型数据,如:
String getString(JSONObject jsonObject, String key, String defaultValue) 得到string类型value
String getString(String jsonData, String key, String defaultValue) 得到string类型value
表示从json中读取某个String类型key的值
getMap(JSONObject jsonObject, String key) 得到map
getMap(String jsonData, String key) 得到map
表示从json中读取某个Map类型key的值
源码可见JSONUtils.java,更多方法及更详细参数介绍可见JSONUtils Api Guide。
7、FileUtils
文件工具类,可用于读写文件及对文件进行操作。如:
readFile(String filePath) 读文件
writeFile(String filePath, String content, boolean append) 写文件
getFileSize(String path) 得到文件大小
deleteFile(String path) 删除文件
源码可见FileUtils.java,更多方法及更详细参数介绍可见FileUtils Api Guide。
8、ResourceUtils
Android Resource工具类,可用于从android资源目录的raw和assets目录读取内容,如:
geFileFromAssets(Context context, String fileName) 得到assets目录下某个文件内容
geFileFromRaw(Context context, int resId) 得到raw目录下某个文件内容
源码可见ResourceUtils.java,更多方法及更详细参数介绍可见ResourceUtils Api Guide。
9、StringUtils
String工具类,可用于常见字符串操作,如:
isEmpty(String str) 判断字符串是否为空或长度为0
isBlank(String str) 判断字符串是否为空或长度为0 或由空格组成
utf8Encode(String str) 以utf-8格式编码
capitalizeFirstLetter(String str) 首字母大写
源码可见StringUtils.java,更多方法及更详细参数介绍可见StringUtils Api Guide。
10、ParcelUtils
Android Parcel工具类,可用于从parcel读取或写入特殊类型数据,如:
readBoolean(Parcel in) 从pacel中读取boolean类型数据
readHashMap(Parcel in, ClassLoader loader) 从pacel中读取map类型数据
writeBoolean(boolean b, Parcel out) 向parcel中写入boolean类型数据
writeHashMap(Map<K, V> map, Parcel out, int flags) 向parcel中写入map类型数据
源码可见ParcelUtils.java,更多方法及更详细参数介绍可见ParcelUtils Api Guide。
11、RandomUtils
随机数工具类,可用于获取固定大小固定字符内的随机数,如:
getRandom(char[] sourceChar, int length) 生成随机字符串,所有字符均在某个字符串内
getRandomNumbers(int length) 生成随机数字
源码可见RandomUtils.java,更多方法及更详细参数介绍可见RandomUtils Api Guide。
12、ArrayUtils
数组工具类,可用于数组常用操作,如:
isEmpty(V[] sourceArray) 判断数组是否为空或长度为0
getLast(V[] sourceArray, V value, V defaultValue, boolean isCircle) 得到数组中某个元素前一个元素,isCircle表示是否循环
getNext(V[] sourceArray, V value, V defaultValue, boolean isCircle) 得到数组中某个元素下一个元素,isCircle表示是否循环
源码可见ArrayUtils.java,更多方法及更详细参数介绍可见ArrayUtils Api Guide。
13、ImageUtils
图片工具类,可用于Bitmap, byte array, Drawable之间进行转换以及图片缩放,目前功能薄弱,后面会进行增强。如:
bitmapToDrawable(Bitmap b) bimap转换为drawable
drawableToBitmap(Drawable d) drawable转换为bitmap
drawableToByte(Drawable d) drawable转换为byte
scaleImage(Bitmap org, float scaleWidth, float scaleHeight) 缩放图片
源码可见ImageUtils.java,更多方法及更详细参数介绍可见ImageUtils Api Guide。
14、ListUtils
List工具类,可用于List常用操作,如:
isEmpty(List<V> sourceList) 判断List是否为空或长度为0
join(List<String> list, String separator) List转换为字符串,并以固定分隔符分割
addDistinctEntry(List<V> sourceList, V entry) 向list中添加不重复元素
源码可见ListUtils.java,更多方法及更详细参数介绍可见ListUtils Api Guide。
15、MapUtils
Map工具类,可用于Map常用操作,如:
isEmpty(Map<K, V> sourceMap) 判断map是否为空或长度为0
parseKeyAndValueToMap(String source, String keyAndValueSeparator, String keyAndValuePairSeparator, boolean ignoreSpace) 字符串解析为map
toJson(Map<String, String> map) map转换为json格式
源码可见MapUtils.java,更多方法及更详细参数介绍可见MapUtils Api Guide。
16、ObjectUtils
Object工具类,可用于Object常用操作,如:
isEquals(Object actual, Object expected) 比较两个对象是否相等
compare(V v1, V v2) 比较两个对象大小
transformIntArray(int[] source) Integer 数组转换为int数组
源码可见ObjectUtils.java,更多方法及更详细参数介绍可见ObjectUtils Api Guide。
17、SerializeUtils
序列化工具类,可用于序列化对象到文件或从文件反序列化对象,如:
deserialization(String filePath) 从文件反序列化对象
serialization(String filePath, Object obj) 序列化对象到文件
源码可见SerializeUtils.java,更多方法及更详细参数介绍可见SerializeUtils Api Guide。
18、SystemUtils
系统信息工具类,可用于得到线程池合适的大小,目前功能薄弱,后面会进行增强。如:
getDefaultThreadPoolSize() 得到跟系统配置相符的线程池大小
源码可见SystemUtils.java,更多方法及更详细参数介绍可见SystemUtils Api Guide。
19、TimeUtils
时间工具类,可用于时间相关操作,如:
getCurrentTimeInLong() 得到当前时间
getTime(long timeInMillis, SimpleDateFormat dateFormat) 将long转换为固定格式时间字符串
源码可见TimeUtils.java,更多方法及更详细参数介绍可见TimeUtils Api Guide。
7.Apache dbUtils应用实例
前段时间使用了Apache Common DbUtils这个工具,在此留个印,以备不时查看。大家都知道现在市面上的数据库访问层的框架很多,当然很多都是包含了OR-Mapping工作步骤的 例如大家常用的Hibernate与Mybatis。当然如果人们要一个纯粹的封装了JDBC的工具类,使用Apache Common DbUtils(下面简称ACD)是个不错的选择,这个工具在JDBC的基础上稍加封装是JDBC的操作更加便捷,在学习使用这个框架的途中你也不需要学 习太多的API类,因为一共也才3个部分(3个包)。
1. org.apache.commons.dbutils (该包中的类主要帮助我们更便捷的操作JDBC)
2. org.apache.commons.dbutils.handlers(该包中的类都是实现org.apache.commons.dbutils.ResultSetHandler接口的实现类)
3. org.apache.commons.dbutils.wrappers(该包中的类主要是封装了对Sql结果集的操作)
使用这个DbUtils的一些优势:
1. 防止了资源的泄露,写一段JDBC的准备代码其实并不麻烦,但是那些操作确实是十分耗时和繁琐的,也会导致有时候数据库连接忘记关闭了导致异常难以追踪。
2. 干净整洁的持久化代码,把数据持久化到数据库的代码被打打削减,剩下的代码能够清晰简洁的表达你的操作目的。
3. 自动把ResultSets中的工具映射到JavaBean中,你不需要手动的使用Setter方法将列值一个个赋予相应的时日,Resultset中的每一个行都大表一个完成的Bean实体。
要学习如何使用这个框架,最简单的方式就是用它写个Demo-CRUD操作,让我们先做个准备动作在Mysql中建立一个测试专用表Visitor。
[sql] view plaincopy在CODE上查看代码片派生到我的代码片
/*创建Visitor*/
CREATE TABLE Visitor
(
Id INT(11) NOT NULL AUTO_INCREMENT,
Name VARCHAR(1000) NOT NULL,
Email VARCHAR(1000) NOT NULL,
Status INT NOT NULL DEFAULT 1,
CreateTime DateTime,
PRIMARY KEY(Id)
)
建完表结构,我们就可以学习怎么利用框架中的Utils类帮助我们完成CRUD-DEMO,其实对于这个框架主要操作的是ResultSetHandler接口的实现类与QueryRunner类
创建对应的JavaBean实体类如下:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
package david.apache.model;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Visitor {
private int id;
private String name;
private String email;
private int status;
private Date createTime;
public Visitor() {
// TODO Auto-generated constructor stub
setCreateTime(new Date());
}
public Visitor(String name, String email) {
this.setName(name);
this.setEmail(email);
this.setStatus(1);
this.setCreateTime(new Date());
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return String.format("{Id: %d, Name: %s, Email: %s, CreateTime: %s}", getId(), getName(), getEmail(),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(getCreateTime()));
}
}
首先我们先新建一个获取Connection的方法:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
private static Connection getConnection() {
Connection conn = null;
try {
Class.forName(CONNECTION_DRIVER_STR);
conn = DriverManager.getConnection(CONNECTION_STR, "root", "123456");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
新建方法(对于里面的自增字段,我们可以采用变通的方法来插入,使用select last_insert_id()方法)
[java] view plaincopy在CODE上查看代码片派生到我的代码片
/*
* 新增Visitor, ScalarHandler的demo
*/
public static void insertVisitor(Visitor visitor) {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "insert into visitor (Name, Email, Status, CreateTime) values (?, ?, ?, ?)";
try {
int count = qr.update(conn, sql, visitor.getName(), visitor.getEmail(), 1, new Date());
BigInteger newId = (BigInteger) qr.query(conn, "select last_insert_id()", new ScalarHandler<BigInteger>(1));
visitor.setId(Integer.valueOf(String.valueOf(newId)));
System.out.println("新增" + count + "条数据=>Id:" + newId);
} catch (SQLException e) {
e.printStackTrace();
}
}
大家可以看到操作的步骤其实很简单,也是写SQL可以了,对于自增字段我们通过select last_insert_id()的方法利用ScalarHandler<BigInteger>实体类来返回达到变通效果。
删除方法
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public static void deleteVisitor(int id) {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "delete from visitor where status>0 and id=?";
try {
int count = qr.update(conn, sql, id);
System.out.println("删除" + count + "条数据。");
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
查询方法
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public static Visitor retrieveVisitor(int id) {
Connection conn = getConnection();
Visitor visitor = null;
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0 and id=?";
try {
visitor = (Visitor) qr.query(conn, sql, new BeanHandler<Visitor>(Visitor.class), id);
System.out.println(visitor);
return visitor;
} catch (Exception e) {
e.printStackTrace();
}
return visitor;
}
更新操作
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public static void updateVisitor(int id) {
Visitor visitor = retrieveVisitor(id);
System.out.println("更新前:" + visitor);
Connection conn = getConnection();
String updateFieldStr = visitor.getName();
QueryRunner qr = new QueryRunner();
String sql = "update visitor set Name = ?, Email = ?, Status = ?, CreateTime = ? where status>0 and Id = ?";
if (updateFieldStr.contains("updated")) {
updateFieldStr = updateFieldStr.substring(0, updateFieldStr.indexOf("updated"));
} else {
updateFieldStr = updateFieldStr + "updated";
}
visitor.setName(updateFieldStr);
try {
int count = qr.update(conn, sql, new Object[] { visitor.getName(), visitor.getName(), visitor.getStatus(),
visitor.getCreateTime(), visitor.getId() });
System.out.println("更新了" + count + "条数据");
System.out.println("更新后:" + visitor);
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
BeanListHandler方法
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public static void getVisitorList() {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0";
try {
List<Visitor> ls = qr.query(conn, sql, new BeanListHandler<Visitor>(Visitor.class));
for (Visitor visitor : ls) {
System.out.println(visitor);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MapHandler操作
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public static void getVisitWithMap(int id) {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0 and id=?";
try {
Map<String, Object> map = qr.query(conn, sql, new MapHandler(), id);
Integer visitorId = Integer.valueOf(map.get("Id").toString());
String visitorName = map.get("Name").toString();
String visitorEmail = map.get("Email").toString();
Integer visitorStatus = Integer.valueOf(map.get("Status").toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date visitorCreateTime = sdf.parse(map.get("CreateTime").toString());
Visitor visitor = new Visitor(visitorName, visitorEmail);
visitor.setId(visitorId);
visitor.setStatus(visitorStatus);
visitor.setCreateTime(visitorCreateTime);
System.out.println(visitor);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
MapListHandler方法
[java] view plaincopy在CODE上查看代码片派生到我的代码片
public static void getVisitWithMapLs() {
Connection conn = getConnection();
QueryRunner qr = new QueryRunner();
String sql = "select * from visitor where status>0";
try {
List<Map<String, Object>> mapLs = qr.query(conn, sql, new MapListHandler());
for (Map<String, Object> map : mapLs) {
Integer visitorId = Integer.valueOf(map.get("Id").toString());
String visitorName = map.get("Name").toString();
String visitorEmail = map.get("Email").toString();
Integer visitorStatus = Integer.valueOf(map.get("Status").toString());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date visitorCreateTime = sdf.parse(map.get("CreateTime").toString());
Visitor visitor = new Visitor(visitorName, visitorEmail);
visitor.setId(visitorId);
visitor.setStatus(visitorStatus);
visitor.setCreateTime(visitorCreateTime);
System.out.println(visitor);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
8. Android异步加载数据的三种实现
-
package com.testasyntextview;
-
-
-
-
import android.app.Activity;
-
import android.app.ProgressDialog;
-
import android.content.Context;
-
import android.os.Bundle;
-
import android.os.Handler;
-
import android.os.Message;
-
import android.text.Html;
-
import android.text.Spanned;
-
import android.view.View;
-
import android.view.View.OnClickListener;
-
import android.widget.Button;
-
import android.widget.TextView;
-
-
-
public class MethodTestAsynTextViewActivity extends Activity {
-
private TextView textView1;
-
private Button button1;
-
private Context context;
-
private ProgressDialog progressDialog;
-
private Spanned html;
-
-
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
context = this;
-
textView1 = (TextView) findViewById(R.id.textView1);
-
button1 = (Button) findViewById(R.id.button1);
-
button1.setOnClickListener(l);
-
-
-
}
-
-
-
private OnClickListener l = new OnClickListener() {
-
-
-
@Override
-
public void onClick(View v) {
-
-
-
progressDialog = ProgressDialog.show(context, "获取数据中", "等待");
-
getHtmlDate();
-
-
-
}
-
};
-
-
-
private void getHtmlDate() {
-
new Thread() {
-
public void run() {
-
Message msg = myHandler.obtainMessage();
-
try {
-
html = HttpUtil.fromHtml(HttpUtil
-
.getHtml(""));
-
msg.what = 0;
-
} catch (Exception e) {
-
e.printStackTrace();
-
msg.what = 1;
-
}
-
-
-
myHandler.sendMessage(msg);
-
}
-
}.start();
-
}
-
-
-
Handler myHandler = new Handler() {
-
-
-
public void handleMessage(Message msg) {
-
switch (msg.what) {
-
case 0:
-
textView1.setText(html);
-
progressDialog.dismiss();
-
break;
-
case 1:
-
textView1.setText("当前无数据");
-
progressDialog.dismiss();
-
break;
-
}
-
super.handleMessage(msg);
-
}
-
};
-
-
-
}
-
<pre name="code" class="java">package com.testasyntextview;
-
-
-
-
-
import android.app.Activity;
-
import android.app.ProgressDialog;
-
import android.content.Context;
-
import android.os.AsyncTask;
-
import android.os.Bundle;
-
import android.os.Handler;
-
import android.os.Message;
-
import android.text.Html;
-
import android.text.Spanned;
-
import android.util.Log;
-
import android.view.View;
-
import android.view.View.OnClickListener;
-
import android.widget.Button;
-
import android.widget.TextView;
-
-
public class TestAsynTextViewActivity extends Activity {
-
private TextView textView1;
-
private Button button1;
-
private Context context;
-
private ProgressDialog progressDialog;
-
private Spanned html;
-
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
context = this;
-
-
progressDialog = new ProgressDialog(context);
-
progressDialog.setTitle("进度条");
-
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
-
-
textView1 = (TextView) findViewById(R.id.textView1);
-
button1 = (Button) findViewById(R.id.button1);
-
button1.setOnClickListener(l);
-
-
}
-
-
private OnClickListener l = new OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
new InitTask().execute("",
-
"");
-
-
}
-
};
-
-
private void getHtmlDate(String url) {
-
-
try {
-
html = HttpUtil.fromHtml(HttpUtil.getHtml(url));
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
class InitTask extends AsyncTask<String, Integer, Long> {
-
protected void onPreExecute() {
-
progressDialog.show();
-
super.onPreExecute();
-
-
}
-
-
protected Long doInBackground(String... params) {
-
-
getHtmlDate(params[0]);
-
publishProgress(50);
-
getHtmlDate(params[1]);
-
publishProgress(100);
-
-
return (long) 1;
-
-
}
-
-
@Override
-
protected void onProgressUpdate(Integer... progress) {
-
-
progressDialog.setProgress(progress[0]);
-
super.onProgressUpdate(progress);
-
Log.e("测试", progress[0] + "");
-
-
}
-
-
@Override
-
protected void onPostExecute(Long result) {
-
-
setTitle(result + "测试");
-
textView1.setText(html);
-
progressDialog.dismiss();
-
-
super.onPostExecute(result);
-
-
}
-
-
}
-
-
}</pre><pre name="code" class="java"></pre>
-
<pre></pre>
-
<p><br>
-
</p>
-
<p></p><pre name="code" class="html">package com.testasyntextview;
-
-
-
-
import android.app.Activity;
-
import android.app.ProgressDialog;
-
import android.content.Context;
-
import android.os.Bundle;
-
import android.os.Handler;
-
import android.os.Message;
-
import android.text.Html;
-
import android.text.Spanned;
-
import android.view.View;
-
import android.view.View.OnClickListener;
-
import android.widget.Button;
-
import android.widget.TextView;
-
-
public class RunableTestAsynTextViewActivity extends Activity {
-
private TextView textView1;
-
private Button button1;
-
private Context context;
-
private ProgressDialog progressDialog;
-
private Spanned html;
-
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
context = this;
-
textView1 = (TextView) findViewById(R.id.textView1);
-
button1 = (Button) findViewById(R.id.button1);
-
button1.setOnClickListener(l);
-
-
}
-
-
private OnClickListener l = new OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
-
progressDialog = ProgressDialog.show(context, "获取数据中", "等待");
-
new Thread(new ThreadDemo()).start();
-
-
}
-
};
-
-
private void getHtmlDate() {
-
try {
-
html = HttpUtil.fromHtml(HttpUtil.getHtml(""));
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
-
}
-
-
class ThreadDemo implements Runnable {
-
public void run() {
-
getHtmlDate();
-
myHandler.sendEmptyMessage(0);
-
}
-
}
-
-
Handler myHandler = new Handler() {
-
-
public void handleMessage(Message msg) {
-
switch (msg.what) {
-
case 0:
-
textView1.setText(html);
-
progressDialog.dismiss();
-
break;
-
case 1:
-
textView1.setText("当前无数据");
-
progressDialog.dismiss();
-
break;
-
}
-
super.handleMessage(msg);
-
}
-
};
-
-
}
-
</pre><p></p>
-
<p><br>
-
</p>
-
<p></p><pre name="code" class="java">package com.testasyntextview;
-
-
import java.io.ByteArrayOutputStream;
-
import java.io.InputStream;
-
import java.net.HttpURLConnection;
-
import java.net.URL;
-
-
import android.graphics.drawable.Drawable;
-
import android.text.Html;
-
import android.text.Spanned;
-
-
public class HttpUtil {
-
public static String getHtml(String path) throws Exception {
-
URL url = new URL(path);
-
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
-
conn.setRequestMethod("GET");
-
conn.setConnectTimeout(5 * 1000);
-
InputStream inStream = conn.getInputStream();
-
byte[] data = readInputStream(inStream);
-
String html = new String(data, "utf-8");
-
return html;
-
}
-
-
public static byte[] readInputStream(InputStream inStream) throws Exception {
-
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-
byte[] buffer = new byte[1024];
-
int len = 0;
-
while ((len = inStream.read(buffer)) != -1) {
-
outStream.write(buffer, 0, len);
-
}
-
inStream.close();
-
return outStream.toByteArray();
-
}
-
-
public static Spanned fromHtml(String html) {
-
Spanned sp = Html.fromHtml(html, new Html.ImageGetter() {
-
@Override
-
public Drawable getDrawable(String source) {
-
InputStream is = null;
-
try {
-
is = (InputStream) new URL(source).getContent();
-
Drawable d = Drawable.createFromStream(is, "src");
-
d.setBounds(0, 0, d.getIntrinsicWidth(),
-
d.getIntrinsicHeight());
-
is.close();
-
return d;
-
} catch (Exception e) {
-
return null;
-
}
-
}
-
}, null);
-
return sp;
-
-
}
-
}
-
</pre><br>
-
<br>
-
<p></p>
-
<br>
-
<br>
-
<br>
|