├── .classpath ├── .gitignore ├── .project ├── .settings └── org.eclipse.jdt.core.prefs ├── AndroidManifest.xml ├── README.md ├── libs ├── android-support-v4.jar ├── fastjson-1.2.5-sources.jar └── fastjson-1.2.5.jar ├── proguard-project.txt ├── project.properties ├── res ├── drawable │ ├── bt_background.xml │ ├── bt_text_color.xml │ └── pb_horizontal.xml └── values │ ├── colors.xml │ ├── dimes.xml │ ├── strings.xml │ └── styles.xml └── src └── com └── kisstools ├── KissEnv.java ├── KissTools.java ├── builder └── RichTextBuilder.java ├── data ├── KVDataBase.java ├── KVDataSet.java └── KVPreference.java ├── formatter └── DiskFormatter.java ├── helper ├── CrashHelper.java └── ViewHolder.java ├── shell ├── ShellResult.java └── ShellUtil.java ├── thread └── KissExecutor.java ├── ui └── FragmentStack.java ├── utils ├── ActivityUtil.java ├── BitmapUtil.java ├── BundleUtil.java ├── ClipboardUtil.java ├── CloseUtil.java ├── CommonUtil.java ├── DebugUtil.java ├── DeviceUtil.java ├── DrawableUtil.java ├── FileUtil.java ├── ImageSize.java ├── IoUtil.java ├── JSONUtil.java ├── KeyboardUtil.java ├── LogUtil.java ├── MediaUtil.java ├── MessageUtil.java ├── NetworkUtil.java ├── NumberUtil.java ├── PackageUtil.java ├── ResourceUtil.java ├── SecurityUtil.java ├── StringUtil.java ├── SystemUtil.java ├── TimeUtil.java ├── ToastUtil.java ├── UrlUtil.java ├── UserUtil.java ├── VerifyUtil.java ├── ViewUtil.java └── ZipUtil.java └── view └── FullscreenView.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | gen 3 | .DS_Store 4 | .git 5 | .svn 6 | lint.xml 7 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | KissTools 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 3 | org.eclipse.jdt.core.compiler.compliance=1.6 4 | org.eclipse.jdt.core.compiler.source=1.6 5 | -------------------------------------------------------------------------------- /AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## Kiss Tools for android 3 | 4 | Keep It Simple, Stupid! 5 | 6 | basic utils classes for android development. 7 | 8 | ## Usage 9 | 10 | First of all, you need to set context for KissTools 11 | 12 | ``` 13 | KissTools.setContext(context); 14 | ``` 15 | 16 | Then enjoy tools below! 17 | 18 | ``` 19 | ├── KissEnv.java 20 | ├── KissTools.java 21 | ├── builder 22 | │   └── RichTextBuilder.java 23 | ├── data 24 | │   ├── KVDataBase.java 25 | │   ├── KVDataSet.java 26 | │   └── KVPreference.java 27 | ├── formatter 28 | │   └── DiskFormatter.java 29 | ├── helper 30 | │   ├── CrashHelper.java 31 | │   └── ViewHolder.java 32 | ├── shell 33 | │   ├── ShellResult.java 34 | │   └── ShellUtil.java 35 | ├── thread 36 | │   └── KissExecutor.java 37 | ├── utils 38 | │   ├── ActivityUtil.java 39 | │   ├── BitmapUtil.java 40 | │   ├── BundleUtil.java 41 | │   ├── ClipboardUtil.java 42 | │   ├── CloseUtil.java 43 | │   ├── CommonUtil.java 44 | │   ├── DebugUtil.java 45 | │   ├── DeviceUtil.java 46 | │   ├── DrawableUtil.java 47 | │   ├── FileUtil.java 48 | │   ├── ImageSize.java 49 | │   ├── IoUtil.java 50 | │   ├── JSONUtil.java 51 | │   ├── KeyboardUtil.java 52 | │   ├── LogUtil.java 53 | │   ├── MediaUtil.java 54 | │   ├── MessageUtil.java 55 | │   ├── NetworkUtil.java 56 | │   ├── NumberUtil.java 57 | │   ├── PackageUtil.java 58 | │   ├── ResourceUtil.java 59 | │   ├── SecurityUtil.java 60 | │   ├── StringUtil.java 61 | │   ├── SystemUtil.java 62 | │   ├── TimeUtil.java 63 | │   ├── ToastUtil.java 64 | │   ├── UrlUtil.java 65 | │   ├── UserUtil.java 66 | │   ├── VerifyUtil.java 67 | │   ├── ViewUtil.java 68 | │   └── ZipUtil.java 69 | └── view 70 | └── FullscreenView.java 71 | ``` 72 | 73 | ## Contact me 74 | 75 | Any further question? 76 | 77 | [Email me](mailto:coder.kiss@gmail.com) please! 78 | 79 | 80 | ## License 81 | 82 | Copyright 2014 Dawson Dong 83 | 84 | Licensed under the Apache License, Version 2.0 (the "License"); 85 | you may not use this file except in compliance with the License. 86 | You may obtain a copy of the License at 87 | 88 | http://www.apache.org/licenses/LICENSE-2.0 89 | 90 | Unless required by applicable law or agreed to in writing, software 91 | distributed under the License is distributed on an "AS IS" BASIS, 92 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 93 | See the License for the specific language governing permissions and 94 | limitations under the License. -------------------------------------------------------------------------------- /libs/android-support-v4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dawsonice/KissTools/0418f41db209622af983b22541ad62ac6925d903/libs/android-support-v4.jar -------------------------------------------------------------------------------- /libs/fastjson-1.2.5-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dawsonice/KissTools/0418f41db209622af983b22541ad62ac6925d903/libs/fastjson-1.2.5-sources.jar -------------------------------------------------------------------------------- /libs/fastjson-1.2.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dawsonice/KissTools/0418f41db209622af983b22541ad62ac6925d903/libs/fastjson-1.2.5.jar -------------------------------------------------------------------------------- /proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-19 15 | android.library=true 16 | -------------------------------------------------------------------------------- /res/drawable/bt_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /res/drawable/bt_text_color.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /res/drawable/pb_horizontal.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | #00000000 5 | #FFFF0000 6 | #FF000000 7 | #FF0000FF 8 | #FF00FF00 9 | #FFFFFFFF 10 | #FFE3E3E3 11 | #FFCCCCCC 12 | #FF999999 13 | #FF828282 14 | #FF4D4D4D 15 | #80F6F6F6 16 | #FFDDDDDD 17 | #FF666666 18 | #FF999999 19 | 20 | -------------------------------------------------------------------------------- /res/values/dimes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 48dp 5 | 4dp 6 | 18sp 7 | 8 | -------------------------------------------------------------------------------- /res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | coder kiss 5 | 6 | -------------------------------------------------------------------------------- /res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 16 | 17 | 24 | 25 | -------------------------------------------------------------------------------- /src/com/kisstools/KissEnv.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools; 6 | 7 | public class KissEnv { 8 | 9 | // line separator 10 | public static final String LINE_SEPARATOR = System 11 | .getProperty("line.separator"); 12 | } 13 | -------------------------------------------------------------------------------- /src/com/kisstools/KissTools.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools; 10 | 11 | import java.lang.ref.WeakReference; 12 | import java.security.InvalidParameterException; 13 | 14 | import android.content.Context; 15 | 16 | public class KissTools { 17 | public static final String TAG = "KissTools"; 18 | private static WeakReference contextRef; 19 | 20 | public static void setContext(Context context) { 21 | if (context == null) { 22 | throw new InvalidParameterException("Invalid context parameter!"); 23 | } 24 | 25 | Context appContext = context.getApplicationContext(); 26 | contextRef = new WeakReference(appContext); 27 | } 28 | 29 | public static Context getApplicationContext() { 30 | Context context = contextRef.get(); 31 | if (context == null) { 32 | throw new InvalidParameterException("Context parameter not set!"); 33 | } else { 34 | return context; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/com/kisstools/builder/RichTextBuilder.java: -------------------------------------------------------------------------------- 1 | package com.kisstools.builder; 2 | 3 | import android.text.Spannable; 4 | import android.text.SpannableString; 5 | import android.text.style.AbsoluteSizeSpan; 6 | import android.text.style.BackgroundColorSpan; 7 | import android.text.style.ForegroundColorSpan; 8 | import android.text.style.ScaleXSpan; 9 | import android.text.style.StrikethroughSpan; 10 | import android.text.style.StyleSpan; 11 | import android.text.style.TypefaceSpan; 12 | 13 | public class RichTextBuilder { 14 | 15 | private SpannableString richText; 16 | private int startIndex; 17 | private int endIndex; 18 | 19 | public RichTextBuilder(SpannableString ss, String key) { 20 | richText = ss; 21 | String text = ss.toString(); 22 | startIndex = text.indexOf(key); 23 | endIndex = startIndex + key.length(); 24 | } 25 | 26 | public RichTextBuilder(String text, String key) { 27 | richText = new SpannableString(text); 28 | startIndex = text.indexOf(key); 29 | endIndex = startIndex + key.length(); 30 | } 31 | 32 | public RichTextBuilder setBackgroud(int color) { 33 | BackgroundColorSpan background = new BackgroundColorSpan(color); 34 | richText.setSpan(background, startIndex, endIndex, 35 | Spannable.SPAN_INCLUSIVE_INCLUSIVE); 36 | return this; 37 | } 38 | 39 | public RichTextBuilder setForeground(int color) { 40 | ForegroundColorSpan foreground = new ForegroundColorSpan(color); 41 | richText.setSpan(foreground, startIndex, endIndex, 42 | Spannable.SPAN_INCLUSIVE_INCLUSIVE); 43 | return this; 44 | } 45 | 46 | public RichTextBuilder setSize(int size) { 47 | AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(size); 48 | richText.setSpan(sizeSpan, startIndex, endIndex, 49 | Spannable.SPAN_INCLUSIVE_INCLUSIVE); 50 | return this; 51 | } 52 | 53 | public RichTextBuilder setScale(float scale) { 54 | ScaleXSpan scaleSpan = new ScaleXSpan(scale); 55 | richText.setSpan(scaleSpan, startIndex, endIndex, 56 | Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 57 | return this; 58 | } 59 | 60 | public RichTextBuilder setStrike() { 61 | StrikethroughSpan strikeSpan = new StrikethroughSpan(); 62 | richText.setSpan(strikeSpan, startIndex, endIndex, 63 | Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 64 | return this; 65 | } 66 | 67 | public RichTextBuilder setTypeface(String typeface) { 68 | TypefaceSpan typeSpan = new TypefaceSpan(typeface); 69 | richText.setSpan(typeSpan, startIndex, endIndex, 70 | Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 71 | return this; 72 | } 73 | 74 | public RichTextBuilder setStyle(int style) { 75 | StyleSpan styleSpan = new StyleSpan(style); 76 | richText.setSpan(styleSpan, startIndex, endIndex, 77 | Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 78 | return this; 79 | } 80 | 81 | public SpannableString build() { 82 | return richText; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/com/kisstools/data/KVDataBase.java: -------------------------------------------------------------------------------- 1 | package com.kisstools.data; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import android.content.Context; 7 | import android.database.Cursor; 8 | import android.database.sqlite.SQLiteDatabase; 9 | import android.database.sqlite.SQLiteOpenHelper; 10 | import android.text.TextUtils; 11 | 12 | import com.kisstools.utils.FileUtil; 13 | 14 | public class KVDataBase extends SQLiteOpenHelper implements KVDataSet { 15 | 16 | public static final String TAG = "KVDataBase"; 17 | 18 | public static final int DB_VERSION = 1; 19 | public static final String DEFAULT_DB_NAME = "kv_data.db"; 20 | public static final String DEFAULT_TABLE_NAME = "key_value"; 21 | 22 | private Context dbContext; 23 | private String dbName; 24 | 25 | public KVDataBase(Context context) { 26 | this(context, DEFAULT_DB_NAME); 27 | } 28 | 29 | public KVDataBase(Context context, String name) { 30 | super(context, name, null, DB_VERSION); 31 | this.dbName = name; 32 | this.dbContext = context; 33 | } 34 | 35 | public void onCreate(SQLiteDatabase db) { 36 | db.execSQL("CREATE TABLE IF NOT EXISTS " 37 | + DEFAULT_TABLE_NAME 38 | + "(id INTEGER, key TEXT UNIQUE, value TEXT NOT NULL, PRIMARY KEY(id, key));"); 39 | } 40 | 41 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 42 | 43 | } 44 | 45 | public String get(String key) { 46 | if (TextUtils.isEmpty(key)) { 47 | return null; 48 | } 49 | 50 | String sql = "SELECT * FROM " + DEFAULT_TABLE_NAME + " WHERE key='" 51 | + key + "'"; 52 | SQLiteDatabase db = getWritableDatabase(); 53 | Cursor cursor = db.rawQuery(sql, null); 54 | String value = null; 55 | if (cursor.moveToFirst()) { 56 | value = cursor.getString(cursor.getColumnIndex("value")); 57 | } 58 | cursor.close(); 59 | db.close(); 60 | 61 | return value; 62 | } 63 | 64 | public boolean set(String key, String value) { 65 | if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) { 66 | return false; 67 | } 68 | 69 | SQLiteDatabase db = getWritableDatabase(); 70 | db.execSQL("INSERT OR REPLACE INTO " + DEFAULT_TABLE_NAME 71 | + "(key, value) VALUES(?, ?)", new Object[] { key, value }); 72 | db.close(); 73 | return true; 74 | } 75 | 76 | public boolean remove(String key) { 77 | if (TextUtils.isEmpty(key)) { 78 | return false; 79 | } 80 | String sql = "DELETE FROM " + DEFAULT_TABLE_NAME + " WHERE key " + "='" 81 | + key + "'"; 82 | SQLiteDatabase db = getWritableDatabase(); 83 | db.execSQL(sql); 84 | db.close(); 85 | return true; 86 | } 87 | 88 | public List list() { 89 | String sql = "SELECT * FROM " + DEFAULT_TABLE_NAME 90 | + " ORDER BY id ASC"; 91 | SQLiteDatabase db = getWritableDatabase(); 92 | Cursor cursor = db.rawQuery(sql, null); 93 | LinkedList values = new LinkedList(); 94 | while (cursor.moveToNext()) { 95 | String value = cursor.getString(cursor.getColumnIndex("value")); 96 | values.addLast(value); 97 | } 98 | cursor.close(); 99 | db.close(); 100 | return values; 101 | } 102 | 103 | @Override 104 | public boolean clear() { 105 | String sql = "DELETE * FROM " + DEFAULT_TABLE_NAME; 106 | SQLiteDatabase db = getWritableDatabase(); 107 | db.execSQL(sql); 108 | db.close(); 109 | return true; 110 | } 111 | 112 | @Override 113 | public boolean delete() { 114 | String absPath = dbContext.getFilesDir().getParent() + "/databases/"; 115 | absPath = absPath + dbName; 116 | boolean succeed = FileUtil.delete(absPath); 117 | return succeed; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/com/kisstools/data/KVDataSet.java: -------------------------------------------------------------------------------- 1 | package com.kisstools.data; 2 | 3 | public interface KVDataSet { 4 | 5 | public String get(String key); 6 | 7 | public boolean set(String key, String value); 8 | 9 | public boolean remove(String key); 10 | 11 | public boolean clear(); 12 | 13 | public boolean delete(); 14 | } 15 | -------------------------------------------------------------------------------- /src/com/kisstools/data/KVPreference.java: -------------------------------------------------------------------------------- 1 | package com.kisstools.data; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | import android.text.TextUtils; 6 | 7 | import com.kisstools.utils.FileUtil; 8 | 9 | public class KVPreference implements KVDataSet { 10 | public static final String TAG = "KVPreference"; 11 | 12 | private static final String DEFAULT_NAME = "kv_sp"; 13 | 14 | private SharedPreferences sp; 15 | private String spName; 16 | private Context spContext; 17 | 18 | public KVPreference(Context context) { 19 | this(context, DEFAULT_NAME); 20 | } 21 | 22 | public KVPreference(Context context, String name) { 23 | this.spContext = context; 24 | this.spName = name; 25 | int mode = Context.MODE_PRIVATE; 26 | sp = spContext.getSharedPreferences(spName, mode); 27 | } 28 | 29 | @Override 30 | public String get(String key) { 31 | String value = sp.getString(key, null); 32 | return value; 33 | } 34 | 35 | @Override 36 | public boolean set(String key, String value) { 37 | if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) { 38 | return false; 39 | } 40 | 41 | boolean succeed = sp.edit().putString(key, value).commit(); 42 | return succeed; 43 | } 44 | 45 | @Override 46 | public boolean remove(String key) { 47 | if (TextUtils.isEmpty(key)) { 48 | return false; 49 | } 50 | 51 | boolean succeed = sp.edit().remove(key).commit(); 52 | return succeed; 53 | } 54 | 55 | @Override 56 | public boolean clear() { 57 | boolean succeed = sp.edit().clear().commit(); 58 | return succeed; 59 | } 60 | 61 | @Override 62 | public boolean delete() { 63 | boolean succeed = clear(); 64 | String absPath = spContext.getFilesDir().getParent() + "/shared_prefs/"; 65 | absPath = absPath + spName + ".xml"; 66 | succeed |= FileUtil.delete(absPath); 67 | return succeed; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/com/kisstools/formatter/DiskFormatter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.formatter; 6 | 7 | import java.text.DecimalFormat; 8 | 9 | public class DiskFormatter { 10 | 11 | public static final int UNIT = 1024; 12 | public static final String FORMAT = "#.00"; 13 | 14 | public static final String B = "B"; 15 | public static final String KB = "KB"; 16 | public static final String MB = "MB"; 17 | public static final String GB = "GB"; 18 | public static final String TB = "TB"; 19 | 20 | private double kbUnit; 21 | private double mbUnit; 22 | private double gbUnit; 23 | private double tbUnit; 24 | 25 | private String format = FORMAT; 26 | private int unit = UNIT; 27 | 28 | public DiskFormatter() { 29 | calUnits(); 30 | } 31 | 32 | public void setUnit(int unit) { 33 | if (unit > 0) { 34 | this.unit = unit; 35 | calUnits(); 36 | } 37 | } 38 | 39 | private void calUnits() { 40 | kbUnit = unit; 41 | mbUnit = unit * kbUnit; 42 | gbUnit = unit * mbUnit; 43 | tbUnit = unit * gbUnit; 44 | } 45 | 46 | public void setFormat(String format) { 47 | this.format = format; 48 | } 49 | 50 | public String format(double size) { 51 | String result = null; 52 | if (size < 0) { 53 | return result; 54 | } else if (size < kbUnit) { 55 | return size + "B"; 56 | } else if (size < mbUnit) { 57 | return division(size, kbUnit) + "KB"; 58 | } else if (size < gbUnit) { 59 | return division(size, mbUnit) + "MB"; 60 | } else if (size < tbUnit) { 61 | return division(size, gbUnit) + "GB"; 62 | } else { 63 | return division(size, tbUnit) + "TB"; 64 | } 65 | } 66 | 67 | private String division(double size, double unit) { 68 | double result = size / unit; 69 | DecimalFormat df = new DecimalFormat(format); 70 | String formatted = df.format(result); 71 | return formatted; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/com/kisstools/helper/CrashHelper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.helper; 6 | 7 | import java.lang.Thread.UncaughtExceptionHandler; 8 | 9 | import android.annotation.SuppressLint; 10 | import android.annotation.TargetApi; 11 | import android.app.Application; 12 | import android.os.Build; 13 | import android.os.Looper; 14 | 15 | import com.kisstools.utils.FileUtil; 16 | import com.kisstools.utils.LogUtil; 17 | import com.kisstools.utils.MediaUtil; 18 | import com.kisstools.utils.StringUtil; 19 | import com.kisstools.utils.TimeUtil; 20 | import com.kisstools.utils.ToastUtil; 21 | 22 | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 23 | public class CrashHelper implements UncaughtExceptionHandler { 24 | 25 | public static final String TAG = "CrashHelper"; 26 | 27 | @SuppressLint("NewApi") 28 | public static final void init(Application application) { 29 | if (Thread.getDefaultUncaughtExceptionHandler() instanceof CrashHelper) { 30 | return; 31 | } 32 | 33 | CrashHelper helper = new CrashHelper(); 34 | Thread.setDefaultUncaughtExceptionHandler(helper); 35 | } 36 | 37 | @Override 38 | public void uncaughtException(Thread thread, Throwable ex) { 39 | final String name = thread.getName(); 40 | 41 | String crashMessage = StringUtil.stringify(ex); 42 | StringBuilder builder = new StringBuilder(); 43 | builder.append("crash in thread " + name); 44 | builder.append("crash detail message:\n"); 45 | builder.append(crashMessage); 46 | 47 | long time = System.currentTimeMillis(); 48 | String format = TimeUtil.FILE_FORMAT; 49 | String fileName = TimeUtil.format(time, format) + ".txt"; 50 | String crashFolder = MediaUtil.getFileDir("crash_log"); 51 | String filePath = crashFolder + "/" + fileName; 52 | LogUtil.e(TAG, builder.toString()); 53 | FileUtil.write(filePath, builder.toString()); 54 | showMessage("application cashed!"); 55 | try { 56 | Thread.sleep(2500); 57 | } catch (Exception e) { 58 | } 59 | System.exit(1); 60 | } 61 | 62 | private void showMessage(final String message) { 63 | new Thread() { 64 | @Override 65 | public void run() { 66 | Looper.prepare(); 67 | ToastUtil.show(message); 68 | Looper.loop(); 69 | } 70 | }.start(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/com/kisstools/helper/ViewHolder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.helper; 6 | 7 | import android.util.SparseArray; 8 | import android.view.View; 9 | 10 | public class ViewHolder { 11 | 12 | private SparseArray views; 13 | private View convertView; 14 | 15 | public static ViewHolder get(View view) { 16 | Object tag = view.getTag(); 17 | if (tag instanceof ViewHolder) { 18 | return (ViewHolder) tag; 19 | } else { 20 | return new ViewHolder(view); 21 | } 22 | } 23 | 24 | private ViewHolder(View view) { 25 | this.views = new SparseArray(); 26 | this.convertView = view; 27 | view.setTag(this); 28 | } 29 | 30 | @SuppressWarnings("unchecked") 31 | public T findViewById(int id) { 32 | View view = views.get(id); 33 | if (view == null) { 34 | view = convertView.findViewById(id); 35 | views.put(id, view); 36 | } 37 | 38 | return (T) view; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/com/kisstools/shell/ShellResult.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.shell; 6 | 7 | public class ShellResult { 8 | 9 | public static final String TAG = "ShellResult"; 10 | 11 | public int resultCode; 12 | public String successMsg; 13 | public String errorMsg; 14 | 15 | public ShellResult() { 16 | this.resultCode = -1; 17 | } 18 | 19 | public ShellResult(int resultCode) { 20 | this.resultCode = resultCode; 21 | } 22 | 23 | public ShellResult(int resultCode, String successMsg, String errorMsg) { 24 | this.resultCode = resultCode; 25 | this.successMsg = successMsg; 26 | this.errorMsg = errorMsg; 27 | } 28 | 29 | public boolean success() { 30 | return (resultCode == 0); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/com/kisstools/shell/ShellUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.shell; 6 | 7 | import java.io.BufferedReader; 8 | import java.io.DataOutputStream; 9 | import java.io.IOException; 10 | import java.io.InputStreamReader; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | import com.kisstools.KissEnv; 15 | import com.kisstools.utils.LogUtil; 16 | import com.kisstools.utils.NumberUtil; 17 | 18 | public class ShellUtil { 19 | public static final String TAG = "ShellUtil"; 20 | 21 | private static final String COMMAND_SU = "su"; 22 | private static final String COMMAND_SH = "sh"; 23 | private static final String CONTEXT_EXIT = "exit" + KissEnv.LINE_SEPARATOR; 24 | private static final String COMMANDS_END = "@=-=@"; 25 | 26 | private DataOutputStream dataOutputStream = null; 27 | private Process shellProcess = null; 28 | private BufferedReader successReader = null; 29 | private BufferedReader errorReader = null; 30 | 31 | public ShellUtil() { 32 | // 33 | } 34 | 35 | public boolean prepare(boolean asRoot) { 36 | try { 37 | shellProcess = Runtime.getRuntime().exec( 38 | asRoot ? COMMAND_SU : COMMAND_SH); 39 | dataOutputStream = new DataOutputStream( 40 | shellProcess.getOutputStream()); 41 | successReader = new BufferedReader(new InputStreamReader( 42 | shellProcess.getInputStream(), "UTF-8")); 43 | errorReader = new BufferedReader(new InputStreamReader( 44 | shellProcess.getErrorStream(), "UTF-8")); 45 | } catch (IOException e) { 46 | e.printStackTrace(); 47 | } 48 | return true; 49 | } 50 | 51 | public ShellResult execute(String command) { 52 | List commands = new ArrayList(); 53 | commands.add(command); 54 | return execute(commands); 55 | } 56 | 57 | private ShellResult execute(List commands) { 58 | // 59 | int resultCode = -1; 60 | if (commands == null || commands.size() == 0) { 61 | return new ShellResult(resultCode, null, null); 62 | } 63 | commands.add("echo " + COMMANDS_END + " $?"); 64 | 65 | String successMsg = null; 66 | String errorMsg = null; 67 | 68 | try { 69 | for (String command : commands) { 70 | if (command == null) { 71 | continue; 72 | } 73 | dataOutputStream.write(command.getBytes()); 74 | dataOutputStream.writeBytes(KissEnv.LINE_SEPARATOR); 75 | dataOutputStream.flush(); 76 | } 77 | 78 | StringBuilder successBuilder = new StringBuilder(); 79 | 80 | String line; 81 | while ((line = successReader.readLine()) != null) { 82 | if (line.contains(COMMANDS_END)) { 83 | break; 84 | } 85 | successBuilder.append(line).append(KissEnv.LINE_SEPARATOR); 86 | } 87 | String[] fields = line.split(" "); 88 | if (fields != null && fields.length >= 2 && fields[1] != null) { 89 | resultCode = NumberUtil.parse(fields[1], resultCode); 90 | } 91 | successMsg = successBuilder.toString(); 92 | 93 | if (resultCode != 0) { 94 | StringBuilder errorBuilder = new StringBuilder(); 95 | while (errorReader.ready() 96 | && (line = errorReader.readLine()) != null) { 97 | errorBuilder.append(line).append(KissEnv.LINE_SEPARATOR); 98 | } 99 | errorMsg = errorBuilder.toString(); 100 | } 101 | } catch (Exception e) { 102 | e.printStackTrace(); 103 | } 104 | return new ShellResult(resultCode, successMsg, errorMsg); 105 | } 106 | 107 | public void exit() { 108 | try { 109 | if (dataOutputStream != null) { 110 | dataOutputStream.writeBytes(CONTEXT_EXIT); 111 | dataOutputStream.flush(); 112 | dataOutputStream.close(); 113 | } 114 | 115 | if (successReader != null) { 116 | successReader.close(); 117 | successReader = null; 118 | } 119 | 120 | if (errorReader != null) { 121 | errorReader.close(); 122 | errorReader = null; 123 | } 124 | 125 | if (shellProcess != null) { 126 | int result = shellProcess.waitFor(); 127 | LogUtil.d(TAG, "exit shell process " + result); 128 | shellProcess.destroy(); 129 | shellProcess = null; 130 | } 131 | } catch (Exception e) { 132 | e.printStackTrace(); 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/com/kisstools/thread/KissExecutor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.thread; 6 | 7 | import java.util.concurrent.BlockingQueue; 8 | import java.util.concurrent.Executor; 9 | import java.util.concurrent.LinkedBlockingQueue; 10 | import java.util.concurrent.ThreadFactory; 11 | import java.util.concurrent.ThreadPoolExecutor; 12 | import java.util.concurrent.TimeUnit; 13 | import java.util.concurrent.atomic.AtomicInteger; 14 | 15 | public class KissExecutor { 16 | 17 | public static final String TAG = "KissExecutor"; 18 | 19 | public static Executor createExecutor(int poolSize, int priority) { 20 | priority = buildPriority(priority); 21 | BlockingQueue taskQueue = new LinkedBlockingQueue(); 22 | ThreadFactory threadFactory = new DefaultThreadFactory(priority, 23 | "kiss-executor-"); 24 | return new ThreadPoolExecutor(poolSize, poolSize, 0L, 25 | TimeUnit.MILLISECONDS, taskQueue, threadFactory); 26 | } 27 | 28 | private static int buildPriority(int priority) { 29 | if (priority < Thread.MIN_PRIORITY) { 30 | return Thread.MIN_PRIORITY; 31 | } else if (priority > Thread.MAX_PRIORITY) { 32 | return Thread.MAX_PRIORITY; 33 | } else { 34 | return priority; 35 | } 36 | } 37 | 38 | private static class DefaultThreadFactory implements ThreadFactory { 39 | 40 | private static final AtomicInteger poolCount = new AtomicInteger(1); 41 | 42 | private final ThreadGroup group; 43 | private final AtomicInteger threadNumber; 44 | private final String namePrefix; 45 | private final int threadPriority; 46 | 47 | DefaultThreadFactory(int threadPriority, String namePrefix) { 48 | this.threadNumber = new AtomicInteger(1); 49 | this.threadPriority = threadPriority; 50 | this.group = Thread.currentThread().getThreadGroup(); 51 | this.namePrefix = namePrefix + poolCount.getAndIncrement(); 52 | } 53 | 54 | @Override 55 | public Thread newThread(Runnable runnable) { 56 | String threadName = namePrefix + "-thread-" 57 | + threadNumber.getAndIncrement(); 58 | Thread thread = new Thread(group, runnable, threadName, 0); 59 | if (thread.isDaemon()) { 60 | thread.setDaemon(false); 61 | } 62 | thread.setPriority(threadPriority); 63 | return thread; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/com/kisstools/ui/FragmentStack.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.ui; 6 | 7 | import java.util.Stack; 8 | 9 | import android.support.v4.app.Fragment; 10 | import android.support.v4.app.FragmentManager; 11 | import android.support.v4.app.FragmentTransaction; 12 | 13 | public class FragmentStack { 14 | 15 | private Stack fragmentStack; 16 | private FragmentManager fragmentManager; 17 | private int contentId; 18 | 19 | public FragmentStack(FragmentManager fragmentManager, int contentId) { 20 | this.fragmentManager = fragmentManager; 21 | this.contentId = contentId; 22 | this.fragmentStack = new Stack(); 23 | } 24 | 25 | public boolean addFragment(T t) { 26 | if (t == null || t.isAdded() || fragmentStack.contains(t)) { 27 | return false; 28 | } 29 | 30 | if (!fragmentStack.isEmpty()) { 31 | T topFragment = fragmentStack.peek(); 32 | hideFragment(topFragment); 33 | } 34 | 35 | fragmentStack.push(t); 36 | FragmentTransaction transaction = fragmentManager.beginTransaction(); 37 | transaction.add(contentId, t).commitAllowingStateLoss(); 38 | return true; 39 | } 40 | 41 | public boolean showFragment(T fragment) { 42 | if (fragment == null || fragment.isVisible()) { 43 | return false; 44 | } 45 | 46 | FragmentTransaction transaction = fragmentManager.beginTransaction(); 47 | transaction.show(fragment).commitAllowingStateLoss(); 48 | 49 | // for the 'show' method will not trigger onResume event 50 | fragment.onResume(); 51 | return true; 52 | } 53 | 54 | private boolean hideFragment(T fragment) { 55 | if (fragment == null || fragment.isHidden()) { 56 | return false; 57 | } 58 | 59 | FragmentTransaction transaction = fragmentManager.beginTransaction(); 60 | transaction.hide(fragment).commitAllowingStateLoss(); 61 | 62 | // for the 'hide' method will not trigger onPause event 63 | fragment.onPause(); 64 | return true; 65 | } 66 | 67 | public boolean popFragment() { 68 | return removeFragment(fragmentStack.size() - 1); 69 | } 70 | 71 | public boolean removeFragment(int index) { 72 | if (fragmentStack.isEmpty()) { 73 | return false; 74 | } 75 | 76 | int stackSize = fragmentStack.size(); 77 | if (index < 0 || index >= stackSize) { 78 | return false; 79 | } 80 | 81 | T fragment = fragmentStack.get(index); 82 | return removeFragment(fragment); 83 | } 84 | 85 | public boolean removeFragment(T t) { 86 | if (t == null || !fragmentStack.contains(t)) { 87 | return false; 88 | } 89 | 90 | FragmentTransaction transaction = fragmentManager.beginTransaction(); 91 | transaction.remove(t).commitAllowingStateLoss(); 92 | 93 | fragmentStack.remove(t); 94 | if (!fragmentStack.isEmpty()) { 95 | T topFragment = fragmentStack.peek(); 96 | showFragment(topFragment); 97 | } 98 | return true; 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/ActivityUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.utils; 6 | 7 | import java.util.List; 8 | 9 | import android.app.Activity; 10 | import android.content.Context; 11 | import android.content.Intent; 12 | import android.content.pm.PackageManager; 13 | import android.content.pm.ResolveInfo; 14 | import android.graphics.Bitmap; 15 | import android.view.View; 16 | 17 | public class ActivityUtil { 18 | 19 | public static void chooseImage(Activity activity, String title, 20 | int requestCode) { 21 | Intent intent = new Intent(); 22 | intent.setType("image/*"); 23 | intent.setAction(Intent.ACTION_PICK); 24 | Intent chooser = Intent.createChooser(intent, title); 25 | startActivityForResult(activity, chooser, requestCode); 26 | } 27 | 28 | public static boolean startActivity(Context context, Class clazz) { 29 | if (context == null || clazz == null) { 30 | return false; 31 | } 32 | Intent intent = new Intent(context, clazz); 33 | return startActivity(context, intent); 34 | } 35 | 36 | public static boolean startActivity(Context context, Intent intent) { 37 | if (context == null || intent == null) { 38 | return false; 39 | } 40 | 41 | if (!(context instanceof Activity)) { 42 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 43 | } 44 | 45 | try { 46 | context.startActivity(intent); 47 | } catch (Exception globalException) { 48 | // catch all exception here 49 | globalException.printStackTrace(); 50 | return false; 51 | } 52 | return true; 53 | } 54 | 55 | public static boolean startActivityForResult(Activity activity, 56 | Intent intent, int requestCode) { 57 | if (activity == null || intent == null) { 58 | return false; 59 | } 60 | 61 | try { 62 | activity.startActivityForResult(intent, requestCode); 63 | } catch (Exception globalException) { 64 | globalException.printStackTrace(); 65 | return false; 66 | } 67 | return true; 68 | } 69 | 70 | public static boolean isIntentResolved(Context context, Intent intent) { 71 | PackageManager packageManager = context.getPackageManager(); 72 | List activities = packageManager.queryIntentActivities( 73 | intent, 0); 74 | return (activities != null && activities.size() > 0); 75 | } 76 | 77 | public static Bitmap captureActivity(Activity activity) { 78 | if (activity == null) { 79 | return null; 80 | } 81 | View view = activity.getWindow().getDecorView().getRootView(); 82 | return ViewUtil.capture(view); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/BitmapUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.BufferedOutputStream; 12 | import java.io.File; 13 | import java.io.FileOutputStream; 14 | import java.io.IOException; 15 | import java.io.InputStream; 16 | 17 | import android.annotation.TargetApi; 18 | import android.content.Context; 19 | import android.content.res.AssetManager; 20 | import android.graphics.Bitmap; 21 | import android.graphics.Bitmap.Config; 22 | import android.graphics.BitmapFactory; 23 | import android.graphics.BitmapFactory.Options; 24 | import android.graphics.BlurMaskFilter; 25 | import android.graphics.Canvas; 26 | import android.graphics.Color; 27 | import android.graphics.Matrix; 28 | import android.graphics.Paint; 29 | import android.graphics.PorterDuff; 30 | import android.graphics.PorterDuff.Mode; 31 | import android.graphics.PorterDuffXfermode; 32 | import android.graphics.Rect; 33 | import android.graphics.RectF; 34 | import android.graphics.drawable.Drawable; 35 | import android.graphics.drawable.GradientDrawable; 36 | import android.media.ExifInterface; 37 | import android.media.ThumbnailUtils; 38 | import android.os.Build; 39 | import android.os.Build.VERSION; 40 | import android.os.Build.VERSION_CODES; 41 | import android.provider.MediaStore.Images; 42 | import android.text.TextUtils; 43 | import android.view.Gravity; 44 | 45 | public class BitmapUtil { 46 | public static final String TAG = "BitmapUtil"; 47 | 48 | public static ImageSize getImageSize(String absPath) { 49 | if (TextUtils.isEmpty(absPath)) { 50 | return null; 51 | } 52 | Options options = getOptions(absPath); 53 | int width = options.outWidth; 54 | int height = options.outHeight; 55 | ImageSize size = new ImageSize(width, height); 56 | return size; 57 | } 58 | 59 | @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) 60 | public static int getImageBytes(Bitmap bitmap) { 61 | if (bitmap == null) { 62 | return 0; 63 | } 64 | int bitmapSize = 0; 65 | if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1) { 66 | bitmapSize = bitmap.getByteCount(); 67 | } else { 68 | bitmapSize = bitmap.getRowBytes() * bitmap.getHeight(); 69 | } 70 | if (bitmapSize < 0) { 71 | bitmapSize = 0; 72 | } 73 | 74 | return bitmapSize; 75 | } 76 | 77 | public static Options getOptions(String absPath) { 78 | if (TextUtils.isEmpty(absPath)) { 79 | return null; 80 | } 81 | Options options = new Options(); 82 | options.inPreferredConfig = Config.ALPHA_8; 83 | options.inJustDecodeBounds = true; 84 | BitmapFactory.decodeFile(absPath, options); 85 | return options; 86 | } 87 | 88 | public static Options getOptions(String absPath, int desireWidth, 89 | int desireHeight) { 90 | if (!FileUtil.exists(absPath) || desireWidth <= 0 || desireHeight <= 0) { 91 | return null; 92 | } 93 | Options options = getOptions(absPath); 94 | int scaleW = sampleSize(options.outWidth, desireWidth); 95 | int scaleH = sampleSize(options.outHeight, desireWidth); 96 | options.inSampleSize = scaleH > scaleW ? scaleH : scaleW; 97 | options.inJustDecodeBounds = false; 98 | return options; 99 | } 100 | 101 | public static Bitmap getAssetBitmap(Context context, String filePath) { 102 | AssetManager assetManager = context.getAssets(); 103 | InputStream ips = null; 104 | Bitmap bitmap = null; 105 | try { 106 | ips = assetManager.open(filePath); 107 | bitmap = BitmapFactory.decodeStream(ips); 108 | } catch (IOException e) { 109 | e.printStackTrace(); 110 | } 111 | return bitmap; 112 | } 113 | 114 | public static Bitmap getImage(String absPath) { 115 | if (!FileUtil.exists(absPath)) { 116 | LogUtil.w(TAG, "invalid file path: " + absPath); 117 | return null; 118 | } 119 | 120 | LogUtil.d(TAG, "decode bitmap " + absPath); 121 | long enter = System.currentTimeMillis(); 122 | Bitmap bitmap = BitmapFactory.decodeFile(absPath); 123 | long delta = System.currentTimeMillis() - enter; 124 | LogUtil.v(TAG, "decode bitmap time " + delta); 125 | 126 | return bitmap; 127 | } 128 | 129 | public static Bitmap getImage(String absPath, ImageSize size) { 130 | if (TextUtils.isEmpty(absPath)) { 131 | return null; 132 | } 133 | 134 | if (ImageSize.valid(size)) { 135 | return getImage(absPath, size.getWidth(), size.getHeight()); 136 | } else { 137 | return getImage(absPath); 138 | } 139 | } 140 | 141 | public static Bitmap getImage(String absPath, int width, int height) { 142 | if (width <= 0 && height <= 0 || !FileUtil.exists(absPath)) { 143 | LogUtil.e(TAG, "invalid parameters absPath " + absPath + " width " 144 | + width + " height " + height); 145 | return null; 146 | } 147 | 148 | LogUtil.d(TAG, "decode bitmap " + absPath + " width " + width 149 | + " height " + height); 150 | long enter = System.currentTimeMillis(); 151 | Options options = getOptions(absPath, width, height); 152 | Bitmap bitmap = BitmapFactory.decodeFile(absPath, options); 153 | if (bitmap == null) { 154 | LogUtil.i(TAG, "decode bitmap failed " + absPath); 155 | return null; 156 | } 157 | 158 | int rotate = getRotate(absPath); 159 | bitmap = rotateImage(bitmap, rotate); 160 | System.gc(); 161 | long delta = System.currentTimeMillis() - enter; 162 | LogUtil.v(TAG, "decode bitmap time " + delta); 163 | return bitmap; 164 | } 165 | 166 | public static Bitmap rotateImage(Bitmap bitmap, int rotate) { 167 | if (bitmap == null) { 168 | return bitmap; 169 | } 170 | Matrix matrix = new Matrix(); 171 | matrix.setRotate(rotate); 172 | Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), 173 | bitmap.getHeight(), matrix, true); 174 | if (rotated != null && !rotated.equals(bitmap)) { 175 | bitmap.recycle(); 176 | bitmap = rotated; 177 | } 178 | return bitmap; 179 | } 180 | 181 | public static boolean saveImage(Bitmap bitmap, String absPath) { 182 | return saveImage(bitmap, absPath, 100); 183 | } 184 | 185 | public static boolean saveImage(Bitmap bitmap, String absPath, int quality) { 186 | if (!FileUtil.create(absPath)) { 187 | LogUtil.w(TAG, "create file failed."); 188 | return false; 189 | } 190 | 191 | try { 192 | File outFile = new File(absPath); 193 | FileOutputStream fos = new FileOutputStream(outFile); 194 | BufferedOutputStream bos = new BufferedOutputStream(fos); 195 | bitmap.compress(Bitmap.CompressFormat.PNG, quality, bos); 196 | bos.flush(); 197 | bos.close(); 198 | } catch (IOException e) { 199 | e.printStackTrace(); 200 | LogUtil.e(TAG, "failed to write image content"); 201 | return false; 202 | } 203 | 204 | return true; 205 | } 206 | 207 | public static Bitmap squareImage(Bitmap bitmap) { 208 | if (bitmap == null) { 209 | return null; 210 | } 211 | int width = bitmap.getWidth(); 212 | int height = bitmap.getHeight(); 213 | if (width == height) { 214 | LogUtil.w(TAG, "no need to square image"); 215 | return bitmap; 216 | } 217 | int x = (height < width) ? ((width - height) / 2) : 0; 218 | int y = (width < height) ? ((height - width) / 2) : 0; 219 | int pixels = width < height ? width : height; 220 | Bitmap square = Bitmap.createBitmap(bitmap, x, y, pixels, pixels); 221 | return square; 222 | } 223 | 224 | public static int getRotate(String absPath) { 225 | if (!FileUtil.exists(absPath)) { 226 | LogUtil.w(TAG, "invalid file path"); 227 | return 0; 228 | } 229 | 230 | ExifInterface exifInterface = null; 231 | try { 232 | exifInterface = new ExifInterface(absPath); 233 | } catch (IOException e) { 234 | e.printStackTrace(); 235 | return 0; 236 | } 237 | 238 | int orientation = exifInterface.getAttributeInt( 239 | ExifInterface.TAG_ORIENTATION, 240 | ExifInterface.ORIENTATION_UNDEFINED); 241 | int rotate = 0; 242 | switch (orientation) { 243 | case ExifInterface.ORIENTATION_ROTATE_90: 244 | rotate = 90; 245 | break; 246 | case ExifInterface.ORIENTATION_ROTATE_180: 247 | rotate = 180; 248 | break; 249 | case ExifInterface.ORIENTATION_ROTATE_270: 250 | rotate = 270; 251 | break; 252 | default: 253 | break; 254 | } 255 | LogUtil.v(TAG, "image rotate " + rotate); 256 | return rotate; 257 | } 258 | 259 | public static Bitmap resizeImage(Bitmap bitmap, int desireWidth, 260 | int desireHeight, boolean isEnlarge) { 261 | if (bitmap == null || desireHeight <= 0 || desireWidth <= 0) { 262 | return null; 263 | } 264 | 265 | int width = bitmap.getWidth(); 266 | int height = bitmap.getHeight(); 267 | 268 | if (width <= 0 || height <= 0) { 269 | return bitmap; 270 | } 271 | if (!isEnlarge && (width < desireWidth && height < desireHeight)) { 272 | return bitmap; 273 | } 274 | float scale; 275 | if (width < height) { 276 | scale = (float) desireHeight / (float) height; 277 | if (desireWidth < width * scale) { 278 | scale = (float) desireWidth / (float) width; 279 | } 280 | } else { 281 | scale = (float) desireWidth / (float) width; 282 | } 283 | 284 | Matrix matrix = new Matrix(); 285 | matrix.postScale(scale, scale); 286 | bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); 287 | 288 | return bitmap; 289 | } 290 | 291 | public final static Bitmap getThumbnail(String absPath, int width, 292 | int height) { 293 | if (!FileUtil.exists(absPath) || width <= 0 || height <= 0) { 294 | return null; 295 | } 296 | Options options = getOptions(absPath, width, height); 297 | try { 298 | Bitmap bitmap = BitmapFactory.decodeFile(absPath, options); 299 | Bitmap result = ThumbnailUtils.extractThumbnail(bitmap, width, 300 | height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT); 301 | // recycle(bitmap); 302 | return result; 303 | } catch (Exception e) { 304 | e.printStackTrace(); 305 | } catch (OutOfMemoryError e) { 306 | e.printStackTrace(); 307 | } 308 | return null; 309 | } 310 | 311 | public final static Bitmap getVideoThumbnail(String absPath, int width, 312 | int height) { 313 | if (!FileUtil.exists(absPath) || width <= 0 || height <= 0) { 314 | return null; 315 | } 316 | Bitmap bitmap = null; 317 | bitmap = ThumbnailUtils.createVideoThumbnail(absPath, 318 | Images.Thumbnails.MINI_KIND); 319 | LogUtil.d(TAG, "bitmap width " + bitmap.getWidth() + " height " 320 | + bitmap.getHeight()); 321 | bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, 322 | ThumbnailUtils.OPTIONS_RECYCLE_INPUT); 323 | return bitmap; 324 | } 325 | 326 | public final static Bitmap waterMark(Context context, Bitmap bitmap, 327 | int waterResId, int gravity) { 328 | Drawable waterPrintDrawable = context.getResources().getDrawable( 329 | waterResId); 330 | int waterPrintWidth = waterPrintDrawable.getIntrinsicWidth(); 331 | int waterPrintHeight = waterPrintDrawable.getIntrinsicHeight(); 332 | int w = bitmap.getWidth(); 333 | int h = bitmap.getHeight(); 334 | if (gravity == Gravity.CENTER) { 335 | waterPrintDrawable.setBounds((w - waterPrintWidth) / 2, 336 | (h - waterPrintHeight) / 2, (w + waterPrintWidth) / 2, 337 | (h + waterPrintHeight) / 2); 338 | } else { 339 | waterPrintDrawable.setBounds((w - waterPrintWidth) / 2, h, 340 | (w + waterPrintWidth) / 2, h + waterPrintHeight); 341 | } 342 | Canvas mCanvas = new Canvas(bitmap); 343 | waterPrintDrawable.draw(mCanvas); 344 | return bitmap; 345 | } 346 | 347 | public final static Bitmap toRounded(Context context, Bitmap bitmap, 348 | int color, int borderDips, int desireWidth) { 349 | try { 350 | Bitmap bitmap0 = squareImage(bitmap); 351 | Bitmap bitmap1 = resizeImage(bitmap0, desireWidth, desireWidth, 352 | true); 353 | int toPX = DeviceUtil.dp2px(borderDips); 354 | int maxBorder = (desireWidth / 2) / 5; 355 | maxBorder = maxBorder > 15 ? 15 : maxBorder; 356 | final int borderSizePx = toPX > maxBorder ? maxBorder : toPX; 357 | 358 | final int size = desireWidth; 359 | int center = (int) (size / 2); 360 | int left = (int) ((desireWidth - size) / 2); 361 | int top = (int) ((desireWidth - size) / 2); 362 | int right = left + size; 363 | int bottom = top + size; 364 | 365 | Bitmap output = Bitmap.createBitmap(size, size, Config.ARGB_8888); 366 | Canvas canvas = new Canvas(output); 367 | final Paint paint = new Paint(); 368 | 369 | final Rect src = new Rect(left, top, right, bottom); 370 | final Rect dst = new Rect(0, 0, size, size); 371 | 372 | canvas.drawARGB(0, 0, 0, 0); 373 | // draw border 374 | paint.setColor(Color.WHITE); 375 | paint.setAntiAlias(true); 376 | int radius = center - borderSizePx; 377 | canvas.drawCircle(center, center, radius, paint); 378 | // draw bitmap 379 | paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); 380 | canvas.drawBitmap(bitmap1, src, dst, paint); 381 | paint.setXfermode(null); 382 | 383 | paint.setStyle(Paint.Style.STROKE); 384 | paint.setStrokeWidth((float) borderSizePx); 385 | radius = center - borderSizePx / 2; 386 | canvas.drawCircle(center, center, radius, paint); 387 | canvas.save(); 388 | recycle(bitmap0, bitmap1, bitmap); 389 | return output; 390 | } catch (Exception e) { 391 | e.printStackTrace(); 392 | } 393 | return bitmap; 394 | } 395 | 396 | public static Bitmap toRoundCorner(Context context, Bitmap bitmap) { 397 | try { 398 | int w = bitmap.getWidth(); 399 | int h = bitmap.getHeight(); 400 | final int delta = DeviceUtil.dp2px(5); 401 | final float roundPx = DeviceUtil.dp2px(14); 402 | final Paint paint = new Paint(); 403 | paint.setAntiAlias(true); 404 | 405 | /* draw round foreground */ 406 | int foreW = w - 2 * delta; 407 | int foreH = h - 2 * delta; 408 | Bitmap foreBmp = Bitmap 409 | .createBitmap(foreW, foreH, Config.ARGB_8888); 410 | Rect rect = new Rect(0, 0, foreW, foreH); 411 | RectF rectF = new RectF(rect); 412 | Canvas canvas0 = new Canvas(foreBmp); 413 | canvas0.drawRoundRect(rectF, roundPx, roundPx, paint); 414 | paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); 415 | canvas0.drawBitmap(bitmap, null, rect, paint); 416 | 417 | /* draw round background */ 418 | Drawable drawable = getDrawbale(0xffffffff, (int) (delta + roundPx)); 419 | drawable.setBounds(0, 0, w, h); 420 | Bitmap result = Bitmap.createBitmap(w, h, Config.ARGB_8888); 421 | Canvas canvas = new Canvas(result); 422 | drawable.draw(canvas); 423 | canvas.drawBitmap(foreBmp, delta, delta, null); 424 | recycle(foreBmp, bitmap); 425 | 426 | return result; 427 | } catch (Exception e) { 428 | e.printStackTrace(); 429 | return bitmap; 430 | } 431 | } 432 | 433 | public final static GradientDrawable getDrawbale(int argb, int radius) { 434 | GradientDrawable drawable = new GradientDrawable(); 435 | drawable.setCornerRadius(radius); 436 | drawable.setColor(argb); 437 | return drawable; 438 | } 439 | 440 | public final static Bitmap drawRing(Bitmap bitmap, int deltaRadius, 441 | int color) { 442 | int w = bitmap.getWidth(); 443 | int dia = deltaRadius * 2 + w; 444 | float radius = (float) dia / 2; 445 | Bitmap resultBitmap = Bitmap.createBitmap(dia, dia, Config.ARGB_8888); 446 | Paint paint = new Paint(); 447 | paint.setColor(color); 448 | paint.setAlpha(128); 449 | paint.setAntiAlias(true); 450 | Canvas canvas = new Canvas(resultBitmap); 451 | canvas.drawCircle(radius, radius, radius, paint); 452 | canvas.drawBitmap(bitmap, deltaRadius, deltaRadius, null); 453 | return resultBitmap; 454 | } 455 | 456 | public final static Bitmap getRound(int argb, int dia) { 457 | float radius = dia / 2; 458 | Bitmap resultBitmap = Bitmap.createBitmap(dia, dia, Config.ARGB_8888); 459 | Paint paint = new Paint(); 460 | paint.setColor(argb); 461 | paint.setAntiAlias(true); 462 | Canvas canvas = new Canvas(resultBitmap); 463 | canvas.drawCircle(radius, radius, radius, paint); 464 | return resultBitmap; 465 | } 466 | 467 | public final static Bitmap stretch(Bitmap bitmap, int height) { 468 | if (bitmap == null) { 469 | return null; 470 | } 471 | if (height <= bitmap.getHeight()) { 472 | return bitmap; 473 | } 474 | int w = bitmap.getWidth(); 475 | int h = bitmap.getHeight(); 476 | int tmpHeight = 1; 477 | Bitmap resultBitmap = Bitmap.createBitmap(w, height, Config.ARGB_8888); 478 | Canvas mCanvas = new Canvas(resultBitmap); 479 | mCanvas.drawBitmap(bitmap, 0, 0, null); 480 | Bitmap tmp = Bitmap 481 | .createBitmap(bitmap, 0, h - tmpHeight, w, tmpHeight); 482 | bitmap.recycle(); 483 | for (int index = 0; index < (height - h) / tmpHeight; index++) { 484 | mCanvas.drawBitmap(tmp, 0, h + index * tmpHeight, null); 485 | } 486 | tmp.recycle(); 487 | return resultBitmap; 488 | } 489 | 490 | public static Bitmap overlay(final Bitmap bitmap) { 491 | if (bitmap == null) { 492 | return null; 493 | } 494 | int width = bitmap.getWidth(); 495 | int height = bitmap.getHeight(); 496 | if (width == 0 || height == 0) { 497 | return null; 498 | } 499 | float rota = 345; 500 | double radians = Math.toRadians(rota); 501 | /* after rotate , the new width is the original width */ 502 | int rotateWidth = (int) (width / (Math.abs(Math.sin(radians)) + Math 503 | .abs(Math.cos(radians)))); 504 | int delta = (width - rotateWidth) / 2; 505 | 506 | // result 507 | Bitmap result = Bitmap.createBitmap(width, width, Config.ARGB_8888); 508 | Canvas canvas = new Canvas(result); 509 | // foreground 510 | Bitmap foreBmp = resizeImage(bitmap, rotateWidth, rotateWidth, true); 511 | // rotate 512 | Matrix matrix = new Matrix(); 513 | matrix.postRotate(rota); 514 | Bitmap rotate = Bitmap.createBitmap(foreBmp, 0, 0, rotateWidth, 515 | rotateWidth, matrix, true); 516 | canvas.drawBitmap(rotate, 0, 0, null); 517 | canvas.drawBitmap(foreBmp, delta, delta, null); 518 | recycle(bitmap, rotate, foreBmp); 519 | return result; 520 | } 521 | 522 | public static Bitmap drawLayoutDropShadow(Bitmap bitmap) { 523 | BlurMaskFilter blurFilter = new BlurMaskFilter(2, 524 | BlurMaskFilter.Blur.OUTER); 525 | Paint shadowPaint = new Paint(); 526 | shadowPaint.setMaskFilter(blurFilter); 527 | int[] offsetXY = { 5, 5 }; 528 | Bitmap shadowBitmap = bitmap.extractAlpha(shadowPaint, offsetXY); 529 | Bitmap shadowImage32 = shadowBitmap.copy(Bitmap.Config.ARGB_8888, true); 530 | Canvas c = new Canvas(shadowImage32); 531 | c.drawBitmap(bitmap, 0, 0, null); 532 | return shadowImage32; 533 | } 534 | 535 | public static Bitmap blur(Bitmap origin, int radius) { 536 | int iterations = 1; 537 | int width = origin.getWidth(); 538 | int height = origin.getHeight(); 539 | int[] inPixels = new int[width * height]; 540 | int[] outPixels = new int[width * height]; 541 | Bitmap bitmap = Bitmap.createBitmap(width, height, 542 | Bitmap.Config.ARGB_8888); 543 | origin.getPixels(inPixels, 0, width, 0, 0, width, height); 544 | for (int index = 0; index < iterations; index++) { 545 | blur(inPixels, outPixels, width, height, radius); 546 | blur(outPixels, inPixels, height, width, radius); 547 | } 548 | bitmap.setPixels(inPixels, 0, width, 0, 0, width, height); 549 | return bitmap; 550 | } 551 | 552 | private static void blur(int[] in, int[] out, int width, int height, 553 | int radius) { 554 | int widthMinus1 = width - 1; 555 | int tableSize = 2 * radius + 1; 556 | int divide[] = new int[256 * tableSize]; 557 | 558 | for (int index = 0; index < 256 * tableSize; index++) { 559 | divide[index] = index / tableSize; 560 | } 561 | 562 | int inIndex = 0; 563 | 564 | for (int y = 0; y < height; y++) { 565 | int outIndex = y; 566 | int ta = 0, tr = 0, tg = 0, tb = 0; 567 | 568 | for (int i = -radius; i <= radius; i++) { 569 | int rgb = in[inIndex + clamp(i, 0, width - 1)]; 570 | ta += (rgb >> 24) & 0xff; 571 | tr += (rgb >> 16) & 0xff; 572 | tg += (rgb >> 8) & 0xff; 573 | tb += rgb & 0xff; 574 | } 575 | 576 | for (int x = 0; x < width; x++) { 577 | out[outIndex] = (divide[ta] << 24) | (divide[tr] << 16) 578 | | (divide[tg] << 8) | divide[tb]; 579 | 580 | int i1 = x + radius + 1; 581 | if (i1 > widthMinus1) 582 | i1 = widthMinus1; 583 | int i2 = x - radius; 584 | if (i2 < 0) 585 | i2 = 0; 586 | int rgb1 = in[inIndex + i1]; 587 | int rgb2 = in[inIndex + i2]; 588 | 589 | ta += ((rgb1 >> 24) & 0xff) - ((rgb2 >> 24) & 0xff); 590 | tr += ((rgb1 & 0xff0000) - (rgb2 & 0xff0000)) >> 16; 591 | tg += ((rgb1 & 0xff00) - (rgb2 & 0xff00)) >> 8; 592 | tb += (rgb1 & 0xff) - (rgb2 & 0xff); 593 | outIndex += height; 594 | } 595 | inIndex += width; 596 | } 597 | } 598 | 599 | private static int clamp(int x, int a, int b) { 600 | return (x < a) ? a : (x > b) ? b : x; 601 | } 602 | 603 | private static int sampleSize(int size, int target) { 604 | int sample = 1; 605 | for (int index = 0; index < 10; index++) { 606 | if (size < target * 2) { 607 | break; 608 | } 609 | size = size / 2; 610 | sample = sample * 2; 611 | } 612 | return sample; 613 | } 614 | 615 | private final static void recycle(Bitmap... bitmaps) { 616 | if (bitmaps == null || bitmaps.length == 0) { 617 | return; 618 | } 619 | for (Bitmap bitmap : bitmaps) { 620 | if (bitmap == null) { 621 | continue; 622 | } 623 | if (!bitmap.isRecycled()) { 624 | bitmap.recycle(); 625 | continue; 626 | } 627 | bitmap = null; 628 | } 629 | System.gc(); 630 | } 631 | } 632 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/BundleUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.util.Set; 12 | 13 | import android.os.Bundle; 14 | import android.text.TextUtils; 15 | 16 | public class BundleUtil { 17 | public static final String TAG = "BundleUtil"; 18 | 19 | public static String getString(Bundle bundle, String key) { 20 | return getString(bundle, key, ""); 21 | } 22 | 23 | private static String getString(Bundle bundle, String key, String df) { 24 | if (df == null) { 25 | df = ""; 26 | } 27 | return getValue(bundle, key, df); 28 | } 29 | 30 | public static boolean getBoolean(Bundle bundle, String key, boolean df) { 31 | return getValue(bundle, key, df); 32 | } 33 | 34 | public static int getInt(Bundle bundle, String key) { 35 | return getInt(bundle, key, 0); 36 | } 37 | 38 | public static int getInt(Bundle bundle, String key, int df) { 39 | return getValue(bundle, key, df); 40 | } 41 | 42 | public static double getDouble(Bundle bundle, String key) { 43 | return getDouble(bundle, key, 0.0); 44 | } 45 | 46 | public static double getDouble(Bundle bundle, String key, double df) { 47 | return getValue(bundle, key, df); 48 | } 49 | 50 | @SuppressWarnings("unchecked") 51 | public static T getValue(Bundle bundle, String key, T df) { 52 | if (bundle == null || TextUtils.isEmpty(key)) { 53 | return df; 54 | } 55 | 56 | if (df == null) { 57 | return df; 58 | } 59 | 60 | if (!bundle.containsKey(key)) { 61 | return df; 62 | } 63 | T value = df; 64 | Object obj = bundle.get(key); 65 | if (obj != null && value.getClass().isAssignableFrom(obj.getClass())) { 66 | value = (T) obj; 67 | } else { 68 | LogUtil.w(TAG, "[key] " + key + " [value] " + obj); 69 | } 70 | return value; 71 | } 72 | 73 | public static final void showContent(Bundle bundle) { 74 | if (bundle == null) { 75 | return; 76 | } 77 | 78 | StringBuilder builder = new StringBuilder(); 79 | builder.append("bundle contnet\n"); 80 | Set keys = bundle.keySet(); 81 | for (String key : keys) { 82 | builder.append("[" + key + "]<->[" + bundle.get(key) + "]\n"); 83 | } 84 | String content = builder.toString(); 85 | LogUtil.d(TAG, content); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/ClipboardUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import android.content.Context; 12 | 13 | public class ClipboardUtil { 14 | public static final String TAG = "ClipboardHelper"; 15 | 16 | @SuppressWarnings("deprecation") 17 | public static boolean setClipboard(Context context, String text) { 18 | android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context 19 | .getSystemService(Context.CLIPBOARD_SERVICE); 20 | clipboard.setText(text); 21 | return true; 22 | } 23 | 24 | @SuppressWarnings("deprecation") 25 | public static String getClipboard(Context context) { 26 | android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context 27 | .getSystemService(Context.CLIPBOARD_SERVICE); 28 | return clipboard.getText().toString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/CloseUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.utils; 6 | 7 | import java.io.Closeable; 8 | import java.io.IOException; 9 | import java.net.ServerSocket; 10 | import java.net.Socket; 11 | 12 | public class CloseUtil { 13 | 14 | public static final void close(Closeable closeable) { 15 | if (closeable != null) { 16 | try { 17 | closeable.close(); 18 | } catch (IOException e) { 19 | 20 | } 21 | } 22 | } 23 | 24 | public static final void close(Socket closeable) { 25 | if (closeable != null) { 26 | try { 27 | closeable.close(); 28 | } catch (IOException e) { 29 | 30 | } 31 | } 32 | } 33 | 34 | public static final void close(ServerSocket closeable) { 35 | if (closeable != null) { 36 | try { 37 | closeable.close(); 38 | } catch (IOException e) { 39 | 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/CommonUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import android.content.Context; 12 | import android.content.pm.ApplicationInfo; 13 | import android.content.pm.PackageManager; 14 | import android.content.pm.PackageManager.NameNotFoundException; 15 | import android.view.View; 16 | import android.view.inputmethod.InputMethodManager; 17 | import android.webkit.MimeTypeMap; 18 | 19 | public class CommonUtil { 20 | public static final String TAG = "CommonUtil"; 21 | 22 | public static void showIME(Context context) { 23 | InputMethodManager imm = (InputMethodManager) context 24 | .getSystemService(Context.INPUT_METHOD_SERVICE); 25 | imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 26 | InputMethodManager.HIDE_NOT_ALWAYS); 27 | } 28 | 29 | public static void hideIME(Context context, View view) { 30 | InputMethodManager imm = (InputMethodManager) context 31 | .getSystemService(Context.INPUT_METHOD_SERVICE); 32 | imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 33 | } 34 | 35 | public final static String getMimeType(String url) { 36 | String extension = MimeTypeMap.getFileExtensionFromUrl(url); 37 | String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( 38 | extension); 39 | return mimeType; 40 | } 41 | 42 | public static int getUid(Context context) { 43 | try { 44 | PackageManager pm = context.getPackageManager(); 45 | ApplicationInfo ai = pm.getApplicationInfo( 46 | context.getPackageName(), PackageManager.GET_ACTIVITIES); 47 | return ai.uid; 48 | } catch (NameNotFoundException e) { 49 | e.printStackTrace(); 50 | } 51 | return 0; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/DebugUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.utils; 6 | 7 | import android.content.Context; 8 | import android.content.pm.ApplicationInfo; 9 | 10 | import com.kisstools.KissTools; 11 | 12 | public class DebugUtil { 13 | 14 | public static boolean isDebugable() { 15 | try { 16 | Context context = KissTools.getApplicationContext(); 17 | ApplicationInfo info = context.getApplicationInfo(); 18 | return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 19 | } catch (Exception e) { 20 | e.printStackTrace(); 21 | } 22 | return false; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/DeviceUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.BufferedReader; 12 | import java.io.FileReader; 13 | import java.io.IOException; 14 | 15 | import android.annotation.TargetApi; 16 | import android.bluetooth.BluetoothAdapter; 17 | import android.content.Context; 18 | import android.content.res.Resources; 19 | import android.graphics.Point; 20 | import android.hardware.Camera; 21 | import android.hardware.Camera.CameraInfo; 22 | import android.hardware.SensorManager; 23 | import android.net.wifi.WifiManager; 24 | import android.os.Build; 25 | import android.provider.Settings.Secure; 26 | import android.telephony.TelephonyManager; 27 | import android.text.TextUtils; 28 | import android.util.DisplayMetrics; 29 | import android.util.TypedValue; 30 | import android.view.Display; 31 | import android.view.WindowManager; 32 | 33 | import com.kisstools.KissTools; 34 | import com.kisstools.shell.ShellResult; 35 | import com.kisstools.shell.ShellUtil; 36 | 37 | //hardware related functions 38 | public class DeviceUtil { 39 | public static final String TAG = "DeviceUtil"; 40 | 41 | @SuppressWarnings("deprecation") 42 | @TargetApi(Build.VERSION_CODES.GINGERBREAD) 43 | public static String getBuildInfo() { 44 | StringBuilder sb = new StringBuilder(); 45 | // alpha sort 46 | sb.append("board: " + Build.BOARD).append("\nbrand: " + Build.BRAND) 47 | .append("\ncpu_abi: " + Build.CPU_ABI) 48 | .append("\ncpu_abi2: " + Build.CPU_ABI2) 49 | .append("\ndevice: " + Build.DEVICE) 50 | .append("\ndisplay: " + Build.DISPLAY) 51 | .append("\nfingerprint: " + Build.FINGERPRINT) 52 | .append("\nhardware: " + Build.HARDWARE) 53 | .append("\nid: " + Build.ID) 54 | .append("\nmanufacture: " + Build.MANUFACTURER) 55 | .append("\nmodel: " + Build.MODEL) 56 | .append("\nproduct: " + Build.PRODUCT) 57 | .append("\nradio: " + Build.RADIO) 58 | .append("\nsdk_int: " + Build.VERSION.SDK_INT); 59 | 60 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { 61 | sb.append("\nserial: " + Build.SERIAL); 62 | } 63 | sb.append("\ntype: " + Build.TYPE).append("\ntags: " + Build.TAGS); 64 | 65 | return sb.toString(); 66 | } 67 | 68 | public static String getProductInfo() { 69 | String brand = android.os.Build.BRAND; 70 | String model = android.os.Build.MODEL; 71 | String manufacture = android.os.Build.MANUFACTURER; 72 | String finalInfo = brand + " " + model + "/" + manufacture; 73 | return finalInfo; 74 | } 75 | 76 | public static final Point getScreenSize() { 77 | Context context = KissTools.getApplicationContext(); 78 | WindowManager wm = (WindowManager) context 79 | .getSystemService(Context.WINDOW_SERVICE); 80 | Display display = wm.getDefaultDisplay(); 81 | 82 | DisplayMetrics metrics = new DisplayMetrics(); 83 | display.getMetrics(metrics); 84 | // since SDK_INT = 1; 85 | int widthPixels = metrics.widthPixels; 86 | int heightPixels = metrics.heightPixels; 87 | // includes window decorations (status bar bar/menu bar) 88 | if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { 89 | try { 90 | widthPixels = (Integer) Display.class.getMethod("getRawWidth") 91 | .invoke(display); 92 | heightPixels = (Integer) Display.class 93 | .getMethod("getRawHeight").invoke(display); 94 | } catch (Exception ignored) { 95 | } 96 | } 97 | // includes window decorations (status bar bar/menu bar) 98 | else if (Build.VERSION.SDK_INT >= 17) { 99 | try { 100 | Point realSize = new Point(); 101 | Display.class.getMethod("getRealSize", Point.class).invoke( 102 | display, realSize); 103 | widthPixels = realSize.x; 104 | heightPixels = realSize.y; 105 | } catch (Exception ignored) { 106 | } 107 | } 108 | return new Point(widthPixels, heightPixels); 109 | } 110 | 111 | public static final float getScreenDensity() { 112 | Context context = KissTools.getApplicationContext(); 113 | Resources resources = context.getResources(); 114 | DisplayMetrics dm = resources.getDisplayMetrics(); 115 | float screenDensity = dm.density; 116 | return screenDensity; 117 | } 118 | 119 | public static int getScreenDensityDpi() { 120 | Context context = KissTools.getApplicationContext(); 121 | Resources resources = context.getResources(); 122 | DisplayMetrics dm = resources.getDisplayMetrics(); 123 | int screenDensityDpi = dm.densityDpi; 124 | return screenDensityDpi; 125 | } 126 | 127 | public static final String getBluetoothMac() { 128 | BluetoothAdapter adapter = null; 129 | String bluetoothMac = null; 130 | try { 131 | adapter = BluetoothAdapter.getDefaultAdapter(); 132 | bluetoothMac = adapter.getAddress(); 133 | } catch (Exception e) { 134 | e.printStackTrace(); 135 | } 136 | 137 | if (!TextUtils.isEmpty(bluetoothMac)) { 138 | bluetoothMac = bluetoothMac.toLowerCase(); 139 | } 140 | return bluetoothMac; 141 | } 142 | 143 | public static final String getWlanMac() { 144 | Context context = KissTools.getApplicationContext(); 145 | String wlanMac = null; 146 | try { 147 | WifiManager wm = (WifiManager) context 148 | .getSystemService(Context.WIFI_SERVICE); 149 | wlanMac = wm.getConnectionInfo().getMacAddress(); 150 | } catch (Exception e) { 151 | e.printStackTrace(); 152 | } 153 | if (!TextUtils.isEmpty(wlanMac)) { 154 | wlanMac = wlanMac.toLowerCase(); 155 | } 156 | return wlanMac; 157 | } 158 | 159 | public static final String getAndroidId() { 160 | Context context = KissTools.getApplicationContext(); 161 | String androidID = null; 162 | try { 163 | androidID = Secure.getString(context.getContentResolver(), 164 | Secure.ANDROID_ID); 165 | } catch (Exception e) { 166 | 167 | } 168 | return androidID; 169 | } 170 | 171 | @TargetApi(Build.VERSION_CODES.GINGERBREAD) 172 | public static final String getSerialId() { 173 | return Build.SERIAL; 174 | } 175 | 176 | public static final String getDeviceId() { 177 | Context context = KissTools.getApplicationContext(); 178 | String deviceIMEI = null; 179 | try { 180 | TelephonyManager teleManager = (TelephonyManager) context 181 | .getSystemService(Context.TELEPHONY_SERVICE); 182 | deviceIMEI = teleManager.getDeviceId(); 183 | } catch (Exception e) { 184 | 185 | } 186 | return deviceIMEI; 187 | } 188 | 189 | public static double getScreenInches() { 190 | Context context = KissTools.getApplicationContext(); 191 | double screenInches = -1; 192 | try { 193 | Resources resources = context.getResources(); 194 | DisplayMetrics dm = resources.getDisplayMetrics(); 195 | Point point = getScreenSize(); 196 | double width = Math.pow(point.x / dm.xdpi, 2); 197 | double height = Math.pow(point.y / dm.ydpi, 2); 198 | screenInches = Math.sqrt(width + height); 199 | } catch (Exception e) { 200 | } 201 | return screenInches; 202 | } 203 | 204 | public static int dp2px(int dip) { 205 | Context context = KissTools.getApplicationContext(); 206 | Resources resources = context.getResources(); 207 | int px = Math 208 | .round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 209 | dip, resources.getDisplayMetrics())); 210 | return px; 211 | } 212 | 213 | public static int px2dp(int px) { 214 | Context context = KissTools.getApplicationContext(); 215 | DisplayMetrics displayMetrics = context.getResources() 216 | .getDisplayMetrics(); 217 | int dp = Math.round(px 218 | / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); 219 | return dp; 220 | } 221 | 222 | public static int sp2px(float sp) { 223 | Context context = KissTools.getApplicationContext(); 224 | final float scale = context.getResources().getDisplayMetrics().scaledDensity; 225 | int px = Math.round(sp * scale); 226 | return px; 227 | } 228 | 229 | @TargetApi(Build.VERSION_CODES.GINGERBREAD) 230 | public static final boolean hasFrontCamera() { 231 | int number = Camera.getNumberOfCameras(); 232 | for (int index = 0; index < number; index++) { 233 | CameraInfo ci = new CameraInfo(); 234 | Camera.getCameraInfo(index, ci); 235 | if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) { 236 | return true; 237 | } 238 | } 239 | return false; 240 | } 241 | 242 | @TargetApi(Build.VERSION_CODES.GINGERBREAD) 243 | public static final boolean hasBackCamera() { 244 | int number = Camera.getNumberOfCameras(); 245 | for (int index = 0; index < number; index++) { 246 | CameraInfo ci = new CameraInfo(); 247 | Camera.getCameraInfo(index, ci); 248 | if (ci.facing == CameraInfo.CAMERA_FACING_BACK) { 249 | return true; 250 | } 251 | } 252 | return false; 253 | } 254 | 255 | public static boolean hasSensor(int type) { 256 | Context context = KissTools.getApplicationContext(); 257 | SensorManager manager = (SensorManager) context 258 | .getSystemService(Context.SENSOR_SERVICE); 259 | return manager.getDefaultSensor(type) != null; 260 | } 261 | 262 | public static final long getTotalMemory() { 263 | String memInfoPath = "/proc/meminfo"; 264 | String str2; 265 | long initial_memory = 0; 266 | try { 267 | FileReader fr = new FileReader(memInfoPath); 268 | BufferedReader bf = new BufferedReader(fr, 8192); 269 | str2 = bf.readLine();// total memory size 270 | String[] as = str2.split("\\s+"); 271 | initial_memory = Integer.valueOf(as[1]).intValue() * 1024; 272 | bf.close(); 273 | return initial_memory; 274 | } catch (IOException e) { 275 | return -1; 276 | } 277 | } 278 | 279 | public static final boolean screenCap(String localPath) { 280 | if (FileUtil.exists(localPath)) { 281 | FileUtil.delete(localPath); 282 | } 283 | 284 | if (!FileUtil.create(localPath)) { 285 | return false; 286 | } 287 | 288 | ShellUtil shell = new ShellUtil(); 289 | // failed to run 'su' command 290 | if (shell.prepare(true)) { 291 | return false; 292 | } 293 | String command = "screencap -p '" + localPath + ","; 294 | ShellResult result = shell.execute(command); 295 | return (result != null && result.success()); 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/DrawableUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import android.graphics.Bitmap; 12 | import android.graphics.Canvas; 13 | import android.graphics.drawable.BitmapDrawable; 14 | import android.graphics.drawable.ColorDrawable; 15 | import android.graphics.drawable.Drawable; 16 | 17 | public class DrawableUtil { 18 | public static final String TAG = "DrawableUtil"; 19 | 20 | public static Drawable fromColor(int color) { 21 | ColorDrawable cd = new ColorDrawable(color); 22 | return cd; 23 | } 24 | 25 | public static Drawable fromBitmap(Bitmap bitmap) { 26 | if (bitmap == null) { 27 | return null; 28 | } 29 | @SuppressWarnings("deprecation") 30 | BitmapDrawable bd = new BitmapDrawable(bitmap); 31 | return bd; 32 | } 33 | 34 | public static Bitmap toBitmap(Drawable drawable) { 35 | if (drawable instanceof BitmapDrawable) { 36 | return ((BitmapDrawable) drawable).getBitmap(); 37 | } 38 | 39 | int width = drawable.getIntrinsicWidth(); 40 | width = width > 0 ? width : 1; 41 | int height = drawable.getIntrinsicHeight(); 42 | height = height > 0 ? height : 1; 43 | 44 | Bitmap bitmap = Bitmap.createBitmap(width, height, 45 | Bitmap.Config.ARGB_8888); 46 | Canvas canvas = new Canvas(bitmap); 47 | drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); 48 | drawable.draw(canvas); 49 | 50 | return bitmap; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/FileUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.File; 12 | import java.io.FileInputStream; 13 | import java.io.FileNotFoundException; 14 | import java.io.FileOutputStream; 15 | import java.io.IOException; 16 | import java.io.InputStream; 17 | import java.io.OutputStream; 18 | import java.io.PrintWriter; 19 | import java.security.MessageDigest; 20 | 21 | import org.apache.http.util.ByteArrayBuffer; 22 | 23 | import android.text.TextUtils; 24 | import android.webkit.MimeTypeMap; 25 | 26 | public class FileUtil { 27 | public static final String TAG = "FileUtil"; 28 | private static final int IO_BUFFER_SIZE = 16384; 29 | 30 | public static boolean create(String absPath) { 31 | return create(absPath, false); 32 | } 33 | 34 | public static boolean create(String absPath, boolean force) { 35 | if (TextUtils.isEmpty(absPath)) { 36 | return false; 37 | } 38 | 39 | if (exists(absPath)) { 40 | return true; 41 | } 42 | 43 | String parentPath = getParent(absPath); 44 | mkdirs(parentPath, force); 45 | 46 | try { 47 | File file = new File(absPath); 48 | return file.createNewFile(); 49 | } catch (Exception e) { 50 | e.printStackTrace(); 51 | } 52 | return false; 53 | } 54 | 55 | public static boolean mkdirs(String absPath) { 56 | return mkdirs(absPath, false); 57 | } 58 | 59 | public static boolean mkdirs(String absPath, boolean force) { 60 | File file = new File(absPath); 61 | if (exists(absPath) && !isFolder(absPath)) { 62 | if (!force) { 63 | return false; 64 | } else { 65 | delete(file); 66 | } 67 | } 68 | try { 69 | file.mkdirs(); 70 | } catch (Exception e) { 71 | e.printStackTrace(); 72 | } 73 | return exists(file); 74 | } 75 | 76 | public static boolean move(String srcPath, String dstPath) { 77 | return move(srcPath, dstPath, false); 78 | } 79 | 80 | public static boolean move(String srcPath, String dstPath, boolean force) { 81 | if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) { 82 | return false; 83 | } 84 | 85 | if (!exists(srcPath)) { 86 | return false; 87 | } 88 | 89 | if (exists(dstPath)) { 90 | if (!force) { 91 | return false; 92 | } else { 93 | delete(dstPath); 94 | } 95 | } 96 | 97 | try { 98 | File srcFile = new File(srcPath); 99 | File dstFile = new File(dstPath); 100 | return srcFile.renameTo(dstFile); 101 | } catch (Exception e) { 102 | e.printStackTrace(); 103 | } 104 | return false; 105 | } 106 | 107 | public static boolean delete(String absPath) { 108 | if (TextUtils.isEmpty(absPath)) { 109 | return false; 110 | } 111 | 112 | File file = new File(absPath); 113 | return delete(file); 114 | } 115 | 116 | public static boolean delete(File file) { 117 | if (!exists(file)) { 118 | return true; 119 | } 120 | 121 | if (file.isFile()) { 122 | return file.delete(); 123 | } 124 | 125 | boolean result = true; 126 | File files[] = file.listFiles(); 127 | for (int index = 0; index < files.length; index++) { 128 | result |= delete(files[index]); 129 | } 130 | result |= file.delete(); 131 | 132 | return result; 133 | } 134 | 135 | public static boolean exists(String absPath) { 136 | if (TextUtils.isEmpty(absPath)) { 137 | return false; 138 | } 139 | File file = new File(absPath); 140 | return exists(file); 141 | } 142 | 143 | public static boolean exists(File file) { 144 | return file == null ? false : file.exists(); 145 | } 146 | 147 | public static boolean childOf(String childPath, String parentPath) { 148 | if (TextUtils.isEmpty(childPath) || TextUtils.isEmpty(parentPath)) { 149 | return false; 150 | } 151 | childPath = cleanPath(childPath); 152 | parentPath = cleanPath(parentPath); 153 | if (childPath.startsWith(parentPath + File.separator)) { 154 | return true; 155 | } 156 | return false; 157 | } 158 | 159 | public static int childCount(String absPath) { 160 | if (!exists(absPath)) { 161 | return 0; 162 | } 163 | File file = new File(absPath); 164 | File[] children = file.listFiles(); 165 | if (children == null || children.length == 0) { 166 | return 0; 167 | } 168 | return children.length; 169 | } 170 | 171 | public static String cleanPath(String absPath) { 172 | if (TextUtils.isEmpty(absPath)) { 173 | return absPath; 174 | } 175 | try { 176 | File file = new File(absPath); 177 | absPath = file.getCanonicalPath(); 178 | } catch (Exception e) { 179 | 180 | } 181 | return absPath; 182 | } 183 | 184 | public static long size(String absPath) { 185 | if (absPath == null) { 186 | return 0; 187 | } 188 | File file = new File(absPath); 189 | return size(file); 190 | } 191 | 192 | public static long size(File file) { 193 | if (!exists(file)) { 194 | return 0; 195 | } 196 | 197 | long length = 0; 198 | if (isFile(file)) { 199 | length = file.length(); 200 | return length; 201 | } 202 | 203 | File files[] = file.listFiles(); 204 | if (files == null || files.length == 0) { 205 | return length; 206 | } 207 | 208 | int size = files.length; 209 | for (int index = 0; index < size; index++) { 210 | File child = files[index]; 211 | length += size(child); 212 | } 213 | return length; 214 | } 215 | 216 | public static boolean copy(String srcPath, String dstPath) { 217 | return copy(srcPath, dstPath, false); 218 | } 219 | 220 | public static boolean copy(String srcPath, String dstPath, boolean force) { 221 | if (TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(dstPath)) { 222 | return false; 223 | } 224 | 225 | // check if copy source equals destination 226 | if (srcPath.equals(dstPath)) { 227 | return true; 228 | } 229 | 230 | // check if source file exists or is a directory 231 | if (!exists(srcPath) || !isFile(srcPath)) { 232 | return false; 233 | } 234 | 235 | // delete old content 236 | if (exists(dstPath)) { 237 | if (!force) { 238 | return false; 239 | } else { 240 | delete(dstPath); 241 | } 242 | } 243 | if (!create(dstPath)) { 244 | return false; 245 | } 246 | 247 | FileInputStream in = null; 248 | FileOutputStream out = null; 249 | 250 | // get streams 251 | try { 252 | in = new FileInputStream(srcPath); 253 | out = new FileOutputStream(dstPath); 254 | } catch (Exception e) { 255 | e.printStackTrace(); 256 | return false; 257 | } 258 | return copy(in, out); 259 | } 260 | 261 | public static boolean copy(InputStream is, OutputStream os) { 262 | if (is == null || os == null) { 263 | return false; 264 | } 265 | 266 | try { 267 | byte[] buffer = new byte[IO_BUFFER_SIZE]; 268 | int length; 269 | while ((length = is.read(buffer)) != -1) { 270 | os.write(buffer, 0, length); 271 | } 272 | os.flush(); 273 | } catch (Exception e) { 274 | e.printStackTrace(); 275 | return false; 276 | } finally { 277 | try { 278 | is.close(); 279 | } catch (Exception ignore) { 280 | } 281 | try { 282 | os.close(); 283 | } catch (Exception ignore) { 284 | 285 | } 286 | } 287 | return true; 288 | } 289 | 290 | public final static boolean isFile(String absPath) { 291 | boolean exists = exists(absPath); 292 | if (!exists) { 293 | return false; 294 | } 295 | 296 | File file = new File(absPath); 297 | return isFile(file); 298 | } 299 | 300 | public final static boolean isFile(File file) { 301 | return file == null ? false : file.isFile(); 302 | } 303 | 304 | public final static boolean isFolder(String absPath) { 305 | boolean exists = exists(absPath); 306 | if (!exists) { 307 | return false; 308 | } 309 | 310 | File file = new File(absPath); 311 | return file.isDirectory(); 312 | } 313 | 314 | public static boolean isSymlink(File file) { 315 | if (file == null) { 316 | return false; 317 | } 318 | 319 | boolean isSymlink = false; 320 | try { 321 | File canon = null; 322 | if (file.getParent() == null) { 323 | canon = file; 324 | } else { 325 | File canonDir = file.getParentFile().getCanonicalFile(); 326 | canon = new File(canonDir, file.getName()); 327 | } 328 | isSymlink = !canon.getCanonicalFile().equals( 329 | canon.getAbsoluteFile()); 330 | } catch (Exception e) { 331 | } 332 | return isSymlink; 333 | } 334 | 335 | public final static String getName(File file) { 336 | return file == null ? null : getName(file.getAbsolutePath()); 337 | } 338 | 339 | public final static String getName(String absPath) { 340 | if (TextUtils.isEmpty(absPath)) { 341 | return absPath; 342 | } 343 | 344 | String fileName = null; 345 | int index = absPath.lastIndexOf("/"); 346 | if (index >= 0 && index < (absPath.length() - 1)) { 347 | fileName = absPath.substring(index + 1, absPath.length()); 348 | } 349 | return fileName; 350 | } 351 | 352 | public final static String getParent(File file) { 353 | return file == null ? null : file.getParent(); 354 | } 355 | 356 | public final static String getParent(String absPath) { 357 | if (TextUtils.isEmpty(absPath)) { 358 | return null; 359 | } 360 | absPath = cleanPath(absPath); 361 | File file = new File(absPath); 362 | return getParent(file); 363 | } 364 | 365 | public static String getStem(File file) { 366 | return file == null ? null : getStem(file.getName()); 367 | } 368 | 369 | public final static String getStem(String fileName) { 370 | if (TextUtils.isEmpty(fileName)) { 371 | return null; 372 | } 373 | 374 | int index = fileName.lastIndexOf("."); 375 | if (index > 0) { 376 | return fileName.substring(0, index); 377 | } else { 378 | return ""; 379 | } 380 | } 381 | 382 | public static String getExtension(File file) { 383 | return file == null ? null : getExtension(file.getName()); 384 | } 385 | 386 | public static String getExtension(String fileName) { 387 | if (TextUtils.isEmpty(fileName)) { 388 | return ""; 389 | } 390 | 391 | int index = fileName.lastIndexOf('.'); 392 | if (index < 0 || index >= (fileName.length() - 1)) { 393 | return ""; 394 | } 395 | return fileName.substring(index + 1); 396 | } 397 | 398 | public static String getMimeType(File file) { 399 | if (file == null) { 400 | return "*/*"; 401 | } 402 | String fileName = file.getName(); 403 | return getMimeType(fileName); 404 | } 405 | 406 | public static String getMimeType(String fileName) { 407 | if (TextUtils.isEmpty(fileName)) { 408 | return "*/*"; 409 | } 410 | String extension = getExtension(fileName); 411 | MimeTypeMap map = MimeTypeMap.getSingleton(); 412 | String type = map.getMimeTypeFromExtension(extension); 413 | if (TextUtils.isEmpty(type)) { 414 | return "*/*"; 415 | } else { 416 | return type; 417 | } 418 | } 419 | 420 | public static String fileSHA1(String absPath) { 421 | if (TextUtils.isEmpty(absPath)) { 422 | return null; 423 | } 424 | File file = new File(absPath); 425 | 426 | if (!file.exists() || file.isDirectory()) { 427 | return null; 428 | } 429 | String fileSHA1 = null; 430 | FileInputStream fis = null; 431 | try { 432 | fis = new FileInputStream(file); 433 | } catch (FileNotFoundException e1) { 434 | e1.printStackTrace(); 435 | return null; 436 | } 437 | MessageDigest messageDigest; 438 | try { 439 | messageDigest = MessageDigest.getInstance("SHA-1"); 440 | byte[] buffer = new byte[IO_BUFFER_SIZE]; 441 | int length = 0; 442 | while ((length = fis.read(buffer)) > 0) { 443 | messageDigest.update(buffer, 0, length); 444 | } 445 | fis.close(); 446 | fileSHA1 = SecurityUtil.bytes2Hex(messageDigest.digest()); 447 | } catch (Exception e) { 448 | e.printStackTrace(); 449 | } finally { 450 | try { 451 | fis.close(); 452 | } catch (IOException e) { 453 | e.printStackTrace(); 454 | } 455 | } 456 | if (!TextUtils.isEmpty(fileSHA1)) { 457 | fileSHA1 = fileSHA1.trim(); 458 | } 459 | return fileSHA1; 460 | } 461 | 462 | public static String fileMD5(String absPath) { 463 | if (TextUtils.isEmpty(absPath)) { 464 | return null; 465 | } 466 | File file = new File(absPath); 467 | if (!file.exists() || file.isDirectory()) { 468 | return null; 469 | } 470 | String fileMD5 = null; 471 | FileInputStream fis = null; 472 | try { 473 | fis = new FileInputStream(file); 474 | } catch (FileNotFoundException e1) { 475 | e1.printStackTrace(); 476 | return null; 477 | } 478 | MessageDigest messageDigest; 479 | try { 480 | messageDigest = MessageDigest.getInstance("MD5"); 481 | byte[] buffer = new byte[IO_BUFFER_SIZE]; 482 | int length = 0; 483 | while ((length = fis.read(buffer)) > 0) { 484 | messageDigest.update(buffer, 0, length); 485 | } 486 | fis.close(); 487 | fileMD5 = SecurityUtil.bytes2Hex(messageDigest.digest()); 488 | } catch (Exception e) { 489 | e.printStackTrace(); 490 | } finally { 491 | try { 492 | fis.close(); 493 | } catch (IOException e) { 494 | e.printStackTrace(); 495 | } 496 | } 497 | if (!TextUtils.isEmpty(fileMD5)) { 498 | fileMD5 = fileMD5.trim(); 499 | } 500 | return fileMD5; 501 | } 502 | 503 | public static final boolean write(String absPath, String text) { 504 | if (!create(absPath, true)) { 505 | return false; 506 | } 507 | 508 | FileOutputStream fos = null; 509 | PrintWriter pw = null; 510 | try { 511 | fos = new FileOutputStream(absPath); 512 | pw = new PrintWriter(fos); 513 | pw.write(text); 514 | pw.flush(); 515 | } catch (Exception e) { 516 | 517 | } finally { 518 | CloseUtil.close(pw); 519 | CloseUtil.close(fos); 520 | } 521 | 522 | return true; 523 | } 524 | 525 | public static final boolean write(String absPath, InputStream ips) { 526 | if (!create(absPath, true)) { 527 | return false; 528 | } 529 | 530 | FileOutputStream fos = null; 531 | try { 532 | fos = new FileOutputStream(absPath); 533 | byte buffer[] = new byte[IO_BUFFER_SIZE]; 534 | int count = ips.read(buffer); 535 | for (; count != -1;) { 536 | fos.write(buffer, 0, count); 537 | count = ips.read(buffer); 538 | } 539 | fos.flush(); 540 | } catch (Exception e) { 541 | // 542 | return false; 543 | } finally { 544 | CloseUtil.close(fos); 545 | } 546 | 547 | return true; 548 | } 549 | 550 | public static final String read(String absPath) { 551 | String text = null; 552 | InputStream ips = null; 553 | try { 554 | ips = new FileInputStream(absPath); 555 | text = read(ips); 556 | } catch (Exception e) { 557 | 558 | } finally { 559 | CloseUtil.close(ips); 560 | } 561 | return text; 562 | } 563 | 564 | public static final String read(InputStream inputStream) { 565 | if (inputStream == null) { 566 | return null; 567 | } 568 | 569 | ByteArrayBuffer baf = new ByteArrayBuffer(IO_BUFFER_SIZE); 570 | byte buffer[] = new byte[IO_BUFFER_SIZE]; 571 | try { 572 | 573 | int count = inputStream.read(buffer); 574 | for (; count != -1;) { 575 | baf.append(buffer, 0, count); 576 | count = inputStream.read(buffer); 577 | } 578 | } catch (Exception e) { 579 | 580 | } 581 | String text = new String(baf.toByteArray()); 582 | return text; 583 | } 584 | 585 | public static final InputStream getStream(String absPath) { 586 | InputStream inputStream = null; 587 | 588 | try { 589 | inputStream = new FileInputStream(absPath); 590 | } catch (Exception e) { 591 | e.printStackTrace(); 592 | } 593 | 594 | return inputStream; 595 | } 596 | } 597 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/ImageSize.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | public class ImageSize { 12 | public static final String TAG = "ImageSize"; 13 | 14 | private int mWidth; 15 | private int mHeight; 16 | 17 | public ImageSize(ImageSize size) { 18 | this.mWidth = size.mWidth; 19 | this.mHeight = size.mHeight; 20 | } 21 | 22 | public ImageSize(int width, int height) { 23 | mWidth = width; 24 | mHeight = height; 25 | } 26 | 27 | public void setWidth(int width) { 28 | this.mWidth = width; 29 | } 30 | 31 | public int getWidth() { 32 | return this.mWidth; 33 | } 34 | 35 | public void setHeight(int height) { 36 | this.mHeight = height; 37 | } 38 | 39 | public int getHeight() { 40 | return this.mHeight; 41 | } 42 | 43 | @Override 44 | public String toString() { 45 | return mWidth + "x" + mHeight; 46 | } 47 | 48 | public static final boolean valid(ImageSize size) { 49 | if (size != null && size.getWidth() > 0 && size.getHeight() > 0) { 50 | return true; 51 | } else { 52 | return false; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/IoUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.utils; 6 | 7 | import java.io.InputStream; 8 | import java.io.OutputStream; 9 | 10 | public class IoUtil { 11 | 12 | // 4k buffer 13 | public static final int BUFFER_SIZE = 4096; 14 | 15 | public static boolean copy(InputStream is, OutputStream os) { 16 | final byte[] buffer = new byte[BUFFER_SIZE]; 17 | try { 18 | int count; 19 | while ((count = is.read(buffer)) != -1) { 20 | os.write(buffer, 0, count); 21 | } 22 | os.flush(); 23 | } catch (Exception e) { 24 | return false; 25 | } 26 | return true; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/JSONUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.math.BigDecimal; 12 | import java.util.Set; 13 | 14 | import android.os.Bundle; 15 | import android.text.TextUtils; 16 | 17 | import com.alibaba.fastjson.JSON; 18 | import com.alibaba.fastjson.JSONArray; 19 | import com.alibaba.fastjson.JSONObject; 20 | 21 | public class JSONUtil { 22 | public static final String TAG = "JSONUtil"; 23 | 24 | public static boolean isJSON(String value) { 25 | if (TextUtils.isEmpty(value)) { 26 | return false; 27 | } 28 | 29 | try { 30 | JSON.parse(value); 31 | } catch (Exception e) { 32 | return false; 33 | } 34 | return true; 35 | } 36 | 37 | public static JSON parseJSON(String value) { 38 | if (TextUtils.isEmpty(value)) { 39 | return null; 40 | } 41 | 42 | JSON jo = null; 43 | try { 44 | jo = (JSON) JSON.parse(value); 45 | } catch (Exception e) { 46 | } 47 | return jo; 48 | } 49 | 50 | public static boolean isJSONObject(String value) { 51 | if (TextUtils.isEmpty(value)) { 52 | return false; 53 | } 54 | 55 | try { 56 | JSON.parseObject(value); 57 | } catch (Exception e) { 58 | return false; 59 | } 60 | return true; 61 | } 62 | 63 | public static JSONObject parseObject(String value) { 64 | if (TextUtils.isEmpty(value)) { 65 | return null; 66 | } 67 | 68 | JSONObject jo = null; 69 | try { 70 | jo = JSON.parseObject(value); 71 | } catch (Exception e) { 72 | } 73 | return jo; 74 | } 75 | 76 | public static boolean isJSONArray(String value) { 77 | if (TextUtils.isEmpty(value)) { 78 | return false; 79 | } 80 | 81 | try { 82 | JSON.parseArray(value); 83 | } catch (Exception e) { 84 | return false; 85 | } 86 | return true; 87 | } 88 | 89 | public static JSONArray parseArray(String value) { 90 | if (TextUtils.isEmpty(value)) { 91 | return null; 92 | } 93 | 94 | JSONArray ja = null; 95 | try { 96 | ja = JSON.parseArray(value); 97 | } catch (Exception e) { 98 | } 99 | return ja; 100 | } 101 | 102 | public static boolean isEmpty(JSONObject jo) { 103 | if (jo == null || jo.isEmpty()) { 104 | return true; 105 | } else { 106 | return false; 107 | } 108 | } 109 | 110 | public static boolean isEmpty(JSONArray ja) { 111 | if (ja == null || ja.isEmpty()) { 112 | return true; 113 | } else { 114 | return false; 115 | } 116 | } 117 | 118 | public static String getString(JSONObject params, String key) { 119 | return getString(params, key, ""); 120 | } 121 | 122 | private static String getString(JSONObject params, String key, String df) { 123 | if (df == null) { 124 | df = ""; 125 | } 126 | return getValue(params, key, df); 127 | } 128 | 129 | public static boolean getBoolean(JSONObject params, String key, boolean df) { 130 | return getValue(params, key, df); 131 | } 132 | 133 | public static int getInt(JSONObject params, String key) { 134 | return getInt(params, key, 0); 135 | } 136 | 137 | public static int getInt(JSONObject params, String key, int df) { 138 | return getValue(params, key, df); 139 | } 140 | 141 | public static JSONObject getJSONObject(JSONObject params, String key) { 142 | return getJSONObject(params, key, null); 143 | } 144 | 145 | public static JSONObject getJSONObject(JSONObject params, String key, 146 | JSONObject df) { 147 | if (df == null) { 148 | df = new JSONObject(); 149 | } 150 | return getValue(params, key, df); 151 | } 152 | 153 | @SuppressWarnings("unchecked") 154 | public static T getValue(JSONObject params, String key, T df) { 155 | if (params == null || params.isEmpty()) { 156 | return df; 157 | } 158 | if (df == null) { 159 | return df; 160 | } 161 | 162 | if (!params.containsKey(key)) { 163 | return df; 164 | } 165 | 166 | T value = df; 167 | Object obj = params.get(key); 168 | if (obj != null && value.getClass().isAssignableFrom(obj.getClass())) { 169 | value = (T) obj; 170 | } else { 171 | LogUtil.w(TAG, "[key] " + key + " [value] " + obj); 172 | } 173 | return value; 174 | } 175 | 176 | public static JSONObject toJSONObject(Bundle bundle) { 177 | JSONObject joBundle = new JSONObject(); 178 | if (bundle == null) { 179 | return joBundle; 180 | } 181 | 182 | Set keys = bundle.keySet(); 183 | for (String key : keys) { 184 | Object value = bundle.get(key); 185 | joBundle.put(key, value); 186 | } 187 | return joBundle; 188 | } 189 | 190 | public static Bundle toBundle(JSONObject params) { 191 | return toBundle(null, params); 192 | } 193 | 194 | public static Bundle toBundle(Bundle bundle, JSONObject params) { 195 | if (bundle == null) { 196 | bundle = new Bundle(); 197 | } 198 | 199 | if (params == null || params.isEmpty()) { 200 | return bundle; 201 | } 202 | 203 | for (String key : params.keySet()) { 204 | Object value = params.get(key); 205 | if (value instanceof Integer) { 206 | bundle.putInt(key, (Integer) value); 207 | } else if (value instanceof Boolean) { 208 | bundle.putBoolean(key, (Boolean) value); 209 | } else if (value instanceof String) { 210 | bundle.putString(key, (String) value); 211 | } else if (value instanceof Long) { 212 | bundle.putLong(key, (Long) value); 213 | } else if (value instanceof Double) { 214 | bundle.putDouble(key, (Double) value); 215 | } else if (value instanceof Float) { 216 | float f = (Float) value; 217 | BigDecimal bd = new BigDecimal(Float.toString(f)); 218 | double dd = bd.doubleValue(); 219 | bundle.putDouble(key, dd); 220 | } else if (value instanceof JSON) { 221 | String jsonStr = ((JSON) value).toJSONString(); 222 | bundle.putString(key, jsonStr); 223 | } 224 | } 225 | 226 | return bundle; 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/KeyboardUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import android.app.Activity; 12 | import android.view.View; 13 | import android.view.ViewTreeObserver.OnGlobalLayoutListener; 14 | 15 | public class KeyboardUtil implements OnGlobalLayoutListener { 16 | static public interface KeyboardListener { 17 | public void onKeyboardVisible(boolean visible); 18 | } 19 | 20 | private int mHeight; 21 | private boolean mVisible; 22 | private View mRootView; 23 | private KeyboardListener mListener; 24 | 25 | public KeyboardUtil(Activity activity) { 26 | mVisible = false; 27 | mHeight = 0; 28 | if (activity == null) { 29 | return; 30 | } 31 | 32 | try { 33 | mRootView = activity.getWindow().getDecorView() 34 | .findViewById(android.R.id.content); 35 | mRootView.getViewTreeObserver().addOnGlobalLayoutListener(this); 36 | } catch (Exception e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | 41 | public void setListener(KeyboardListener listener) { 42 | this.mListener = listener; 43 | } 44 | 45 | @Override 46 | public void onGlobalLayout() { 47 | if (mHeight == 0) { 48 | mHeight = mRootView.getMeasuredHeight(); 49 | return; 50 | } 51 | 52 | if (mListener == null) { 53 | return; 54 | } 55 | 56 | int height = mRootView.getHeight(); 57 | 58 | if (!mVisible && mHeight > (height + 100)) { 59 | mVisible = true; 60 | mListener.onKeyboardVisible(mVisible); 61 | mHeight = height; 62 | } else if (mVisible && mHeight < (height - 100)) { 63 | mVisible = false; 64 | mListener.onKeyboardVisible(mVisible); 65 | mHeight = height; 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/LogUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.BufferedOutputStream; 12 | import java.io.File; 13 | import java.io.FileOutputStream; 14 | import java.io.IOException; 15 | import java.io.RandomAccessFile; 16 | 17 | import android.text.TextUtils; 18 | import android.util.Log; 19 | 20 | import com.kisstools.KissTools; 21 | 22 | public class LogUtil { 23 | public final static String TAG = "LogUtil"; 24 | 25 | private static final String LOG_FORMAT = "%1$s\n%2$s"; 26 | 27 | public final static int LOG_VERBOSE = Log.VERBOSE; 28 | public final static int LOG_DEBUG = Log.DEBUG; 29 | public final static int LOG_INFO = Log.INFO; 30 | public final static int LOG_WARN = Log.WARN; 31 | public final static int LOG_ERROR = Log.ERROR; 32 | public final static int LOG_ASSERT = Log.ASSERT; 33 | public final static int LOG_NONE = Log.ASSERT + 1; 34 | 35 | public final static int LOG_DEFAULT = LOG_VERBOSE; 36 | private static int mLogPriority = LOG_DEFAULT; 37 | 38 | private final static int LOG_MAX_MEM = 16384; // 16k 39 | private final static int LOG_MAX_LEN = 2048; // 2k 40 | private final static long LOG_FILE_LEN = 4194304; // 4MB 41 | 42 | private static boolean mFileLog = false; 43 | private static StringBuilder mStringBuilder = new StringBuilder();; 44 | 45 | public static void setLogPriority(int priority) { 46 | mLogPriority = priority; 47 | } 48 | 49 | public static int getLogPriority() { 50 | return mLogPriority; 51 | } 52 | 53 | public static void setFileLog(boolean fileLog) { 54 | mFileLog = fileLog; 55 | } 56 | 57 | public static void v(String tag, String msg) { 58 | log(Log.VERBOSE, null, tag, msg); 59 | } 60 | 61 | public static void d(String tag, String msg) { 62 | log(LOG_DEBUG, null, tag, msg); 63 | } 64 | 65 | public static void i(String tag, String msg) { 66 | log(LOG_INFO, null, tag, msg); 67 | } 68 | 69 | public static void w(String tag, String msg) { 70 | log(LOG_WARN, null, tag, msg); 71 | } 72 | 73 | public static void e(String tag, String msg) { 74 | log(LOG_ERROR, null, tag, msg); 75 | } 76 | 77 | public static void e(Throwable ex) { 78 | log(LOG_ERROR, ex, null, null); 79 | } 80 | 81 | public static void e(String tag, Throwable ex) { 82 | log(LOG_ERROR, ex, tag, null); 83 | } 84 | 85 | public static void e(String tag, String msg, Throwable ex) { 86 | log(LOG_ERROR, ex, tag, msg); 87 | } 88 | 89 | public static void destroy() { 90 | writeLog(); 91 | } 92 | 93 | private static void log(int priority, Throwable ex, String tag, 94 | String message) { 95 | if (priority < mLogPriority) { 96 | return; 97 | } 98 | 99 | if (ex != null) { 100 | message = message == null ? ex.getMessage() : message; 101 | String logBody = Log.getStackTraceString(ex); 102 | message = String.format(LOG_FORMAT, message, logBody); 103 | } 104 | 105 | String text = message; 106 | int partLen = 0; 107 | int length = text.length(); 108 | while (text != null && length > 0) { 109 | partLen = length > LOG_MAX_LEN ? LOG_MAX_LEN : length; 110 | String partLog = text.substring(0, partLen); 111 | Log.println(priority, tag, partLog); 112 | text = text.substring(partLen); 113 | length = text.length(); 114 | } 115 | 116 | if (mFileLog) { 117 | synchronized (mStringBuilder) { 118 | mStringBuilder.append(message); 119 | int builderLen = mStringBuilder.length(); 120 | if (builderLen > LOG_MAX_MEM) { 121 | writeLog(); 122 | } 123 | } 124 | } 125 | } 126 | 127 | private static void writeLog() { 128 | new Thread() { 129 | public void run() { 130 | write2LogFile(); 131 | } 132 | }.start(); 133 | } 134 | 135 | private static void write2LogFile() { 136 | String log = null; 137 | synchronized (mStringBuilder) { 138 | log = mStringBuilder.toString(); 139 | int length = mStringBuilder.length(); 140 | mStringBuilder.delete(0, length); 141 | } 142 | 143 | String logFolder = getLogFolder(); 144 | if (TextUtils.isEmpty(logFolder)) { 145 | return; 146 | } 147 | 148 | String logPath = logFolder + "/bestutils.log"; 149 | File logFile = new File(logPath); 150 | if (!logFile.exists()) { 151 | FileUtil.create(logPath); 152 | } 153 | if (logFile.length() >= LOG_FILE_LEN) { 154 | resizeLogFile(logFile); 155 | } 156 | 157 | try { 158 | FileOutputStream fos = new FileOutputStream(logFile, true); 159 | fos.write(log.getBytes()); 160 | fos.close(); 161 | } catch (Exception e) { 162 | e.printStackTrace(); 163 | } 164 | } 165 | 166 | private static void resizeLogFile(File logFile) { 167 | BufferedOutputStream bos = null; 168 | RandomAccessFile raf = null; 169 | try { 170 | String logFolder = getLogFolder(); 171 | if (TextUtils.isEmpty(logFolder)) { 172 | return; 173 | } 174 | String tempLog = logFolder + "/temp.log"; 175 | FileUtil.delete(tempLog); 176 | if (!FileUtil.create(tempLog)) { 177 | return; 178 | } 179 | 180 | bos = new BufferedOutputStream(new FileOutputStream(tempLog)); 181 | raf = new RandomAccessFile(logFile, "r"); 182 | raf.seek(LOG_FILE_LEN / 2); 183 | int readLen = 0; 184 | byte[] readBuff = new byte[1024]; 185 | while ((readLen = raf.read(readBuff)) != -1) { 186 | bos.write(readBuff, 0, readLen); 187 | } 188 | 189 | logFile.delete(); 190 | FileUtil.move(tempLog, logFile.getAbsolutePath()); 191 | } catch (IOException e) { 192 | e.printStackTrace(); 193 | } finally { 194 | try { 195 | if (bos != null) { 196 | bos.close(); 197 | } 198 | if (raf != null) { 199 | raf.close(); 200 | } 201 | } catch (IOException e) { 202 | e.printStackTrace(); 203 | } 204 | } 205 | } 206 | 207 | private static final String getLogFolder() { 208 | File cacheFolder = KissTools.getApplicationContext().getExternalCacheDir(); 209 | String logFolder = cacheFolder.getAbsolutePath() + "/KissTools"; 210 | return logFolder; 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/MediaUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.File; 12 | 13 | import android.content.Context; 14 | import android.os.Environment; 15 | import android.text.TextUtils; 16 | 17 | import com.kisstools.KissTools; 18 | 19 | public class MediaUtil { 20 | public static final String TAG = "MediaUtil"; 21 | 22 | public static String getAppDir() { 23 | String appDir = null; 24 | Context context = KissTools.getApplicationContext(); 25 | if (mediaMounted()) { 26 | File fileDir = context.getExternalFilesDir(""); 27 | if (fileDir.exists()) { 28 | appDir = FileUtil.getParent(fileDir); 29 | } 30 | } 31 | 32 | if (appDir == null) { 33 | File fileDir = context.getFilesDir(); 34 | if (fileDir.exists()) { 35 | appDir = FileUtil.getParent(fileDir); 36 | } 37 | } 38 | return appDir; 39 | } 40 | 41 | public static String getFileDir(String dirName) { 42 | String appDir = getAppDir(); 43 | if (TextUtils.isEmpty(appDir)) { 44 | return null; 45 | } 46 | 47 | if (TextUtils.isEmpty(dirName)) { 48 | return appDir; 49 | } 50 | String fileDir = appDir + "/" + dirName; 51 | return fileDir; 52 | } 53 | 54 | public static boolean mediaMounted() { 55 | String state = Environment.getExternalStorageState(); 56 | if (Environment.MEDIA_MOUNTED.equals(state)) { 57 | return true; 58 | } else { 59 | return false; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/MessageUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.util.LinkedList; 12 | 13 | import android.content.BroadcastReceiver; 14 | import android.content.Intent; 15 | import android.content.IntentFilter; 16 | import android.support.v4.content.LocalBroadcastManager; 17 | import android.text.TextUtils; 18 | 19 | import com.kisstools.KissTools; 20 | 21 | public class MessageUtil { 22 | public static final String TAG = "Messager"; 23 | 24 | public static final String BROADCAST_PARAM = "broadcast_param"; 25 | public static final String REQUEST_ACTION = "request_action"; 26 | public static final String RESPONSE_ACTION = "response_action"; 27 | 28 | private static volatile MessageUtil instance; 29 | 30 | public static final MessageUtil sharedInstance() { 31 | synchronized (MessageUtil.class) { 32 | if (instance == null) { 33 | instance = new MessageUtil(); 34 | } 35 | } 36 | return instance; 37 | } 38 | 39 | private LocalBroadcastManager mManager; 40 | private LinkedList mReceivers; 41 | 42 | private MessageUtil() { 43 | mReceivers = new LinkedList(); 44 | mManager = LocalBroadcastManager.getInstance(KissTools 45 | .getApplicationContext()); 46 | } 47 | 48 | public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 49 | if (receiver == null || filter == null) { 50 | LogUtil.e(TAG, "invalid parameters"); 51 | return; 52 | } 53 | 54 | synchronized (mManager) { 55 | if (mReceivers.contains(receiver)) { 56 | LogUtil.e(TAG, "unregister old receiver!"); 57 | mManager.unregisterReceiver(receiver); 58 | } 59 | 60 | mReceivers.addLast(receiver); 61 | mManager.registerReceiver(receiver, filter); 62 | } 63 | } 64 | 65 | public void unregisterReceiver(BroadcastReceiver receiver) { 66 | if (receiver == null) { 67 | LogUtil.e(TAG, "invalid parameters!"); 68 | return; 69 | } 70 | 71 | if (!mReceivers.contains(receiver)) { 72 | return; 73 | } 74 | 75 | synchronized (mManager) { 76 | mReceivers.remove(receiver); 77 | mManager.unregisterReceiver(receiver); 78 | } 79 | } 80 | 81 | public void sendBroadcast(Intent intent) { 82 | if (intent == null) { 83 | return; 84 | } 85 | String action = intent.getAction(); 86 | LogUtil.d(TAG, "sendBroadcast " + action); 87 | mManager.sendBroadcast(intent); 88 | } 89 | 90 | public void sendBroadcast(String action, String info) { 91 | if (TextUtils.isEmpty(action)) { 92 | LogUtil.e(TAG, "invalid action"); 93 | return; 94 | } 95 | 96 | Intent intent = new Intent(action); 97 | if (!TextUtils.isEmpty(info)) { 98 | intent.putExtra(BROADCAST_PARAM, info); 99 | } 100 | mManager.sendBroadcast(intent); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/NetworkUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import android.content.BroadcastReceiver; 12 | import android.content.Context; 13 | import android.content.Intent; 14 | import android.content.IntentFilter; 15 | import android.net.ConnectivityManager; 16 | import android.net.NetworkInfo; 17 | import android.telephony.TelephonyManager; 18 | 19 | import com.kisstools.KissTools; 20 | 21 | public class NetworkUtil { 22 | public static final String TAG = "NetworkHelper"; 23 | 24 | public interface NetworkListener { 25 | public void onNetworkChanged(NetworkType ot, NetworkType nt); 26 | }; 27 | 28 | public static enum NetworkType { 29 | WIFI_FAST, MOBILE_FAST, MOBILE_MIDDLE, MOBILE_SLOW, NONE, 30 | } 31 | 32 | private NetworkType type; 33 | private NetworkListener listener; 34 | 35 | private BroadcastReceiver receiver = new BroadcastReceiver() { 36 | 37 | @Override 38 | public void onReceive(Context context, Intent intent) { 39 | updateNetwork(); 40 | } 41 | }; 42 | 43 | private NetworkUtil() { 44 | type = NetworkType.NONE; 45 | updateNetwork(); 46 | 47 | IntentFilter filter = new IntentFilter(); 48 | filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 49 | KissTools.getApplicationContext().registerReceiver(receiver, filter); 50 | } 51 | 52 | public final synchronized NetworkType getNetworkType() { 53 | return type; 54 | } 55 | 56 | public final void setListener(NetworkListener l) { 57 | listener = l; 58 | } 59 | 60 | private final void updateNetwork() { 61 | NetworkInfo networkInfo = getNetworkInfo(); 62 | NetworkType t = type; 63 | type = checkType(networkInfo); 64 | if (type != t && listener != null) { 65 | listener.onNetworkChanged(t, type); 66 | } 67 | LogUtil.i(TAG, "network [type] " + type); 68 | } 69 | 70 | private final synchronized NetworkInfo getNetworkInfo() { 71 | Context context = KissTools.getApplicationContext(); 72 | ConnectivityManager manager = (ConnectivityManager) context 73 | .getSystemService(Context.CONNECTIVITY_SERVICE); 74 | return manager.getActiveNetworkInfo(); 75 | } 76 | 77 | private static NetworkType checkType(NetworkInfo info) { 78 | if (info == null || !info.isConnected()) { 79 | return NetworkType.NONE; 80 | } 81 | 82 | int type = info.getType(); 83 | int subType = info.getSubtype(); 84 | if ((type == ConnectivityManager.TYPE_WIFI) 85 | || (type == ConnectivityManager.TYPE_ETHERNET)) { 86 | return NetworkType.WIFI_FAST; 87 | } 88 | 89 | if (type == ConnectivityManager.TYPE_MOBILE) { 90 | switch (subType) { 91 | case TelephonyManager.NETWORK_TYPE_GPRS: 92 | case TelephonyManager.NETWORK_TYPE_EDGE: 93 | case TelephonyManager.NETWORK_TYPE_CDMA: 94 | case TelephonyManager.NETWORK_TYPE_1xRTT: 95 | case TelephonyManager.NETWORK_TYPE_IDEN: 96 | return NetworkType.MOBILE_SLOW; // 2G 97 | 98 | case TelephonyManager.NETWORK_TYPE_UMTS: 99 | case TelephonyManager.NETWORK_TYPE_EVDO_0: 100 | case TelephonyManager.NETWORK_TYPE_EVDO_A: 101 | case TelephonyManager.NETWORK_TYPE_HSDPA: 102 | case TelephonyManager.NETWORK_TYPE_HSUPA: 103 | case TelephonyManager.NETWORK_TYPE_HSPA: 104 | case TelephonyManager.NETWORK_TYPE_EVDO_B: 105 | case TelephonyManager.NETWORK_TYPE_EHRPD: 106 | case TelephonyManager.NETWORK_TYPE_HSPAP: 107 | return NetworkType.MOBILE_MIDDLE;// 3G 108 | 109 | case TelephonyManager.NETWORK_TYPE_LTE: 110 | return NetworkType.MOBILE_FAST; // 4G 111 | } 112 | } 113 | 114 | return NetworkType.NONE; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/NumberUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.utils; 6 | 7 | import java.math.BigDecimal; 8 | 9 | import android.text.TextUtils; 10 | 11 | public class NumberUtil { 12 | 13 | public static double multiply(double d1, double d2) { 14 | BigDecimal bd1 = new BigDecimal(Double.toString(d1)); 15 | BigDecimal bd2 = new BigDecimal(Double.toString(d2)); 16 | double result = bd1.multiply(bd2).doubleValue(); 17 | return result; 18 | } 19 | 20 | public static int parse(String text, int dv) { 21 | if (TextUtils.isEmpty(text)) { 22 | return dv; 23 | } 24 | 25 | text = text.trim(); 26 | int value = dv; 27 | try { 28 | value = Integer.parseInt(text); 29 | } catch (Exception ignore) { 30 | } 31 | return value; 32 | } 33 | 34 | public static double parse(String text, double dv) { 35 | if (TextUtils.isEmpty(text)) { 36 | return dv; 37 | } 38 | 39 | text = text.trim(); 40 | double value = dv; 41 | try { 42 | value = Double.parseDouble(text); 43 | } catch (Exception ignore) { 44 | } 45 | return value; 46 | } 47 | 48 | public static float parse(String text, float dv) { 49 | if (TextUtils.isEmpty(text)) { 50 | return dv; 51 | } 52 | 53 | text = text.trim(); 54 | float value = dv; 55 | try { 56 | value = Float.parseFloat(text); 57 | } catch (Exception ignore) { 58 | } 59 | return value; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/PackageUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.utils; 6 | 7 | import java.util.List; 8 | 9 | import android.content.Context; 10 | import android.content.Intent; 11 | import android.content.pm.PackageInfo; 12 | import android.content.pm.PackageManager; 13 | import android.content.pm.ResolveInfo; 14 | import android.net.Uri; 15 | import android.text.TextUtils; 16 | 17 | import com.kisstools.KissTools; 18 | import com.kisstools.shell.ShellResult; 19 | import com.kisstools.shell.ShellUtil; 20 | 21 | public class PackageUtil { 22 | 23 | private static final String BOOT_START_PERMISSION = "android.permission.RECEIVE_BOOT_COMPLETED"; 24 | 25 | // install package normally 26 | public static final boolean install(String filePath) { 27 | if (!FileUtil.exists(filePath)) { 28 | return false; 29 | } 30 | Intent intent = new Intent(Intent.ACTION_VIEW); 31 | intent.setDataAndType(Uri.parse("file://" + filePath), 32 | "application/vnd.android.package-archive"); 33 | Context context = KissTools.getApplicationContext(); 34 | return ActivityUtil.startActivity(context, intent); 35 | } 36 | 37 | // install package silently 38 | public static final boolean silentInstall(String filePath) { 39 | if (!FileUtil.exists(filePath)) { 40 | return false; 41 | } 42 | 43 | String command = new StringBuilder().append("pm install ") 44 | .append(filePath.replace(" ", "\\ ")).toString(); 45 | ShellUtil shell = new ShellUtil(); 46 | shell.prepare(true); 47 | ShellResult result = shell.execute(command); 48 | return (result.resultCode == 0); 49 | } 50 | 51 | // uninstall package normally 52 | public static final boolean uninstall(String packageName) { 53 | if (TextUtils.isEmpty(packageName)) { 54 | return false; 55 | } 56 | 57 | Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" 58 | + packageName)); 59 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 60 | Context context = KissTools.getApplicationContext(); 61 | return ActivityUtil.startActivity(context, intent); 62 | } 63 | 64 | public static boolean silentUninstall(String packageName, boolean keepData) { 65 | if (TextUtils.isEmpty(packageName)) { 66 | return false; 67 | } 68 | 69 | String command = new StringBuilder().append("pm uninstall") 70 | .append(keepData ? " -k " : " ") 71 | .append(packageName.replace(" ", "\\ ")).toString(); 72 | ShellUtil shell = new ShellUtil(); 73 | shell.prepare(true); 74 | ShellResult result = shell.execute(command); 75 | return (result.resultCode == 0); 76 | } 77 | 78 | public static PackageInfo getPackageInfo(String packageName) { 79 | PackageInfo packageInfo = null; 80 | Context context = KissTools.getApplicationContext(); 81 | PackageManager packageManager = context.getPackageManager(); 82 | try { 83 | int flags = PackageManager.GET_ACTIVITIES | PackageManager.GET_GIDS 84 | | PackageManager.GET_CONFIGURATIONS 85 | | PackageManager.GET_INSTRUMENTATION 86 | | PackageManager.GET_PERMISSIONS 87 | | PackageManager.GET_PROVIDERS 88 | | PackageManager.GET_RECEIVERS 89 | | PackageManager.GET_SERVICES 90 | | PackageManager.GET_SIGNATURES 91 | | PackageManager.GET_UNINSTALLED_PACKAGES; 92 | packageInfo = packageManager.getPackageInfo(packageName, flags); 93 | } catch (Exception ignore) { 94 | } 95 | return packageInfo; 96 | } 97 | 98 | public static boolean isBootStart(String packageName) { 99 | Context context = KissTools.getApplicationContext(); 100 | PackageManager pm = context.getPackageManager(); 101 | int flag = pm.checkPermission(BOOT_START_PERMISSION, packageName); 102 | return (flag == PackageManager.PERMISSION_GRANTED); 103 | } 104 | 105 | public static boolean isAutoStart(String packageName) { 106 | Context context = KissTools.getApplicationContext(); 107 | PackageManager pm = context.getPackageManager(); 108 | Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 109 | List resolveInfoList = pm.queryBroadcastReceivers(intent, 110 | PackageManager.GET_DISABLED_COMPONENTS); 111 | for (ResolveInfo ri : resolveInfoList) { 112 | String pn = ri.loadLabel(pm).toString(); 113 | if (packageName.equals(pn)) { 114 | return true; 115 | } 116 | } 117 | return false; 118 | } 119 | 120 | public static String getPackageDir(String packageName) { 121 | String applicationDir = null; 122 | PackageInfo pi = getPackageInfo(packageName); 123 | if (pi != null) { 124 | applicationDir = pi.applicationInfo.dataDir; 125 | } 126 | return applicationDir; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/ResourceUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import android.content.Context; 12 | import android.graphics.drawable.Drawable; 13 | 14 | import com.kisstools.KissTools; 15 | 16 | public class ResourceUtil { 17 | 18 | public static final String getString(int resId) { 19 | Context context = KissTools.getApplicationContext(); 20 | if (context == null || resId <= 0) { 21 | return null; 22 | } 23 | try { 24 | return context.getString(resId); 25 | } catch (Exception e) { 26 | e.printStackTrace(); 27 | } 28 | return null; 29 | } 30 | 31 | public static final String getString(int resId, Object... args) { 32 | Context context = KissTools.getApplicationContext(); 33 | if (context == null || resId <= 0) { 34 | return null; 35 | } 36 | try { 37 | return context.getString(resId, args); 38 | } catch (Exception e) { 39 | e.printStackTrace(); 40 | } 41 | return null; 42 | } 43 | 44 | public static final Drawable getDrawable(int resId) { 45 | Context context = KissTools.getApplicationContext(); 46 | if (context == null || resId <= 0) { 47 | return null; 48 | } 49 | try { 50 | return context.getResources().getDrawable(resId); 51 | } catch (Exception e) { 52 | e.printStackTrace(); 53 | } 54 | return null; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/SecurityUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.security.MessageDigest; 12 | import java.util.Locale; 13 | 14 | import android.text.TextUtils; 15 | 16 | public class SecurityUtil { 17 | public static final String TAG = "SecurityUtil"; 18 | 19 | public static String getMD5(String text) { 20 | String md5 = null; 21 | if (TextUtils.isEmpty(text)) { 22 | return md5; 23 | } 24 | MessageDigest md5Digest = null; 25 | try { 26 | md5Digest = MessageDigest.getInstance("MD5"); 27 | } catch (Exception e) { 28 | e.printStackTrace(); 29 | return md5; 30 | } 31 | char[] charArray = text.toCharArray(); 32 | byte[] byteArray = new byte[charArray.length]; 33 | 34 | for (int index = 0; index < charArray.length; index++) { 35 | byteArray[index] = (byte) charArray[index]; 36 | } 37 | 38 | byte[] md5Bytes = md5Digest.digest(byteArray); 39 | StringBuffer hexValue = new StringBuffer(); 40 | 41 | for (int index = 0; index < md5Bytes.length; index++) { 42 | int val = ((int) md5Bytes[index]) & 0xff; 43 | if (val < 16) { 44 | hexValue.append("0"); 45 | } 46 | hexValue.append(Integer.toHexString(val)); 47 | } 48 | 49 | md5 = hexValue.toString(); 50 | return md5; 51 | } 52 | 53 | public static String bytes2Hex(byte[] bytes) { 54 | String hs = ""; 55 | String stmp = ""; 56 | for (int n = 0; n < bytes.length; n++) { 57 | stmp = (Integer.toHexString(bytes[n] & 0XFF)); 58 | if (stmp.length() == 1) { 59 | hs += "0" + stmp; 60 | } else { 61 | hs += stmp; 62 | } 63 | } 64 | return hs.toLowerCase(Locale.ENGLISH); 65 | } 66 | 67 | public static String getSHA1(String text) { 68 | String sha1 = null; 69 | if (TextUtils.isEmpty(text)) { 70 | return sha1; 71 | } 72 | MessageDigest sha1Digest = null; 73 | try { 74 | sha1Digest = MessageDigest.getInstance("SHA-1"); 75 | } catch (Exception e) { 76 | return sha1; 77 | } 78 | byte[] textBytes = text.getBytes(); 79 | sha1Digest.update(textBytes, 0, text.length()); 80 | byte[] sha1hash = sha1Digest.digest(); 81 | return bytes2Hex(sha1hash); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/StringUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.PrintWriter; 12 | import java.io.StringWriter; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.regex.Matcher; 16 | import java.util.regex.Pattern; 17 | 18 | import android.text.TextUtils; 19 | 20 | public class StringUtil { 21 | public static final String TAG = "StringUtil"; 22 | 23 | public static final String regEmail = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; 24 | public static final String regCnChar = "[\u4E00-\u9FFF]+"; 25 | public static final String regIpAddress = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; 26 | 27 | public static final String cutText(String text, int maxLength) { 28 | if (isEmpty(text) || maxLength < 0) { 29 | return text; 30 | } 31 | int length = text.length(); 32 | if (length > maxLength) { 33 | return text.substring(0, maxLength); 34 | } 35 | return text; 36 | } 37 | 38 | public static boolean isEmail(String text) { 39 | if (TextUtils.isEmpty(text)) { 40 | return false; 41 | } 42 | 43 | Pattern pattern = Pattern.compile(regEmail); 44 | Matcher matcher = pattern.matcher(text); 45 | return matcher.find(); 46 | } 47 | 48 | public static boolean isIp4Address(String text) { 49 | if (TextUtils.isEmpty(text)) { 50 | return false; 51 | } 52 | 53 | Pattern pattern = Pattern.compile(regIpAddress); 54 | Matcher macher = pattern.matcher(text); 55 | return macher.matches(); 56 | } 57 | 58 | public static String stringify(Throwable t) { 59 | if (t == null) { 60 | return null; 61 | } 62 | StringWriter sw = new StringWriter(); 63 | PrintWriter pw = new PrintWriter(sw); 64 | t.printStackTrace(pw); 65 | return sw.toString(); 66 | } 67 | 68 | public static boolean isEmpty(String text) { 69 | if (text == null || text.length() == 0) { 70 | return true; 71 | } 72 | return false; 73 | } 74 | 75 | private static Pattern urlPattern = Pattern 76 | .compile("((?:(http|https|Http|Https):\\/\\/" 77 | + "(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|" 78 | + "(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\" 79 | + "+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})" 80 | + "?\\@)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\-\\_]{0,64}\\.)" 81 | + "+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])" 82 | + "|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|" 83 | + "coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]" 84 | + "|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])" 85 | + "|(?:jobs|j[emop])|k[eghimnrwyz]|l[abcikrstuvy]|" 86 | + "(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|" 87 | + "(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|" 88 | + "qa|r[eouw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])" 89 | + "|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]" 90 | + "|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}" 91 | + "|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]" 92 | + "|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))" 93 | + "(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~%\\-\\." 94 | + "\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"); 95 | 96 | public static List extractUrls(String text) { 97 | List urls = new ArrayList(); 98 | 99 | Matcher matcher = urlPattern.matcher(text); 100 | while (matcher.find()) { 101 | urls.add(matcher.group()); 102 | } 103 | 104 | return urls; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/SystemUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.ByteArrayOutputStream; 12 | import java.io.File; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.lang.reflect.Field; 16 | import java.lang.reflect.Method; 17 | import java.util.List; 18 | 19 | import android.annotation.TargetApi; 20 | import android.app.Activity; 21 | import android.app.ActivityManager; 22 | import android.app.AlarmManager; 23 | import android.app.PendingIntent; 24 | import android.app.admin.DevicePolicyManager; 25 | import android.content.ContentResolver; 26 | import android.content.Context; 27 | import android.content.Intent; 28 | import android.content.pm.PackageInfo; 29 | import android.content.pm.PackageManager; 30 | import android.content.res.Resources; 31 | import android.net.Uri; 32 | import android.net.wifi.WifiManager; 33 | import android.os.Build; 34 | import android.os.Build.VERSION_CODES; 35 | import android.os.Handler; 36 | import android.os.Looper; 37 | import android.provider.Settings; 38 | import android.text.TextUtils; 39 | import android.util.DisplayMetrics; 40 | import android.util.TypedValue; 41 | import android.view.MotionEvent; 42 | import android.view.View; 43 | 44 | import com.kisstools.KissTools; 45 | 46 | public class SystemUtil { 47 | public static final String TAG = "SystemUtil"; 48 | public static final int MAX_BRIGHTNESS = 255; 49 | public static final int MIN_BRIGHTNESS = 0; 50 | 51 | public static int getActionBarHeight(Context context) { 52 | TypedValue tv = new TypedValue(); 53 | int height = 0; 54 | int resId = android.R.attr.actionBarSize; 55 | if (context.getTheme().resolveAttribute(resId, tv, true)) { 56 | DisplayMetrics dm = context.getResources().getDisplayMetrics(); 57 | height = TypedValue.complexToDimensionPixelSize(tv.data, dm); 58 | } 59 | return height; 60 | } 61 | 62 | public static int getStatusBarHeight(Context context) { 63 | int height = 0; 64 | if (context == null) { 65 | return height; 66 | } 67 | Resources resources = context.getResources(); 68 | int resId = resources.getIdentifier("status_bar_height", "dimen", 69 | "android"); 70 | if (resId > 0) { 71 | height = resources.getDimensionPixelSize(resId); 72 | } 73 | return height; 74 | } 75 | 76 | public static final String getVersion() { 77 | String version = Build.VERSION.RELEASE; 78 | Field[] fields = Build.VERSION_CODES.class.getFields(); 79 | for (Field field : fields) { 80 | String fieldName = field.getName(); 81 | int fieldValue = -1; 82 | try { 83 | fieldValue = field.getInt(new Object()); 84 | } catch (Exception e) { 85 | e.printStackTrace(); 86 | } 87 | if (fieldValue == Build.VERSION.SDK_INT) { 88 | version = version + " : " + fieldName + " : " + fieldValue; 89 | } 90 | } 91 | return version; 92 | } 93 | 94 | public static boolean installedApp(String packageName) { 95 | Context context = KissTools.getApplicationContext(); 96 | PackageInfo packageInfo = null; 97 | if (TextUtils.isEmpty(packageName)) { 98 | return false; 99 | } 100 | final PackageManager packageManager = context.getPackageManager(); 101 | List packageInfos = packageManager.getInstalledPackages(0); 102 | if (packageInfos == null) { 103 | return false; 104 | } 105 | for (int index = 0; index < packageInfos.size(); index++) { 106 | packageInfo = packageInfos.get(index); 107 | final String name = packageInfo.packageName; 108 | if (packageName.equals(name)) { 109 | return true; 110 | } 111 | } 112 | return false; 113 | } 114 | 115 | public static void uninstallApp(String packageName) { 116 | Context context = KissTools.getApplicationContext(); 117 | boolean installed = installedApp(packageName); 118 | if (!installed) { 119 | ToastUtil.show("package_not_installed"); 120 | return; 121 | } 122 | 123 | boolean isRooted = isRooted(); 124 | if (isRooted) { 125 | runRootCmd("pm uninstall " + packageName); 126 | } else { 127 | Uri uri = UrlUtil.parse("package:" + packageName); 128 | Intent intent = new Intent(Intent.ACTION_DELETE, uri); 129 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 130 | context.startActivity(intent); 131 | } 132 | } 133 | 134 | public static int getBrightness() { 135 | Context context = KissTools.getApplicationContext(); 136 | int screenBrightness = 255; 137 | try { 138 | screenBrightness = Settings.System.getInt( 139 | context.getContentResolver(), 140 | Settings.System.SCREEN_BRIGHTNESS); 141 | } catch (Exception e) { 142 | e.printStackTrace(); 143 | } 144 | return screenBrightness; 145 | } 146 | 147 | public static void setBrightness(int brightness) { 148 | Context context = KissTools.getApplicationContext(); 149 | try { 150 | if (brightness < MIN_BRIGHTNESS) { 151 | brightness = MIN_BRIGHTNESS; 152 | } 153 | if (brightness > MAX_BRIGHTNESS) { 154 | brightness = MAX_BRIGHTNESS; 155 | } 156 | ContentResolver resolver = context.getContentResolver(); 157 | Uri uri = Settings.System 158 | .getUriFor(Settings.System.SCREEN_BRIGHTNESS); 159 | Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, 160 | brightness); 161 | resolver.notifyChange(uri, null); 162 | } catch (Exception e) { 163 | e.printStackTrace(); 164 | } 165 | } 166 | 167 | public static int getBrightnessMode() { 168 | Context context = KissTools.getApplicationContext(); 169 | int brightnessMode = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL; 170 | try { 171 | brightnessMode = Settings.System.getInt( 172 | context.getContentResolver(), 173 | Settings.System.SCREEN_BRIGHTNESS_MODE); 174 | } catch (Exception e) { 175 | e.printStackTrace(); 176 | } 177 | return brightnessMode; 178 | } 179 | 180 | // 1 auto, 0 manual 181 | public static void setBrightnessMode(int brightnessMode) { 182 | Context context = KissTools.getApplicationContext(); 183 | try { 184 | Settings.System.putInt(context.getContentResolver(), 185 | Settings.System.SCREEN_BRIGHTNESS_MODE, brightnessMode); 186 | } catch (Exception e) { 187 | e.printStackTrace(); 188 | } 189 | } 190 | 191 | public static void setWifiEnabled(boolean enable) { 192 | Context context = KissTools.getApplicationContext(); 193 | try { 194 | WifiManager wifiManager = (WifiManager) context 195 | .getSystemService(Context.WIFI_SERVICE); 196 | wifiManager.setWifiEnabled(enable); 197 | } catch (Exception e) { 198 | e.printStackTrace(); 199 | } 200 | } 201 | 202 | public static boolean isWifiEnabled() { 203 | Context context = KissTools.getApplicationContext(); 204 | boolean enabled = false; 205 | try { 206 | WifiManager wifiManager = (WifiManager) context 207 | .getSystemService(Context.WIFI_SERVICE); 208 | enabled = wifiManager.isWifiEnabled(); 209 | } catch (Exception e) { 210 | e.printStackTrace(); 211 | } 212 | return enabled; 213 | } 214 | 215 | public static boolean isRooted() { 216 | String binaryName = "su"; 217 | boolean rooted = false; 218 | String[] places = { "/sbin/", "/system/bin/", "/system/xbin/", 219 | "/data/local/xbin/", "/data/local/bin/", "/system/sd/xbin/", 220 | "/system/bin/failsafe/", "/data/local/" }; 221 | for (String where : places) { 222 | if (new File(where + binaryName).exists()) { 223 | rooted = true; 224 | break; 225 | } 226 | } 227 | return rooted; 228 | } 229 | 230 | public static boolean isSimulator() { 231 | return (Build.FINGERPRINT != null && Build.FINGERPRINT 232 | .contains("generic")) 233 | || "google_sdk".equals(Build.PRODUCT) 234 | || "google_sdk".equals(Build.MODEL) 235 | || "goldfish".equals(Build.HARDWARE); 236 | } 237 | 238 | public static boolean hasPermission(String permission) { 239 | Context context = KissTools.getApplicationContext(); 240 | int result = context.checkCallingOrSelfPermission(permission); 241 | return (result == PackageManager.PERMISSION_GRANTED); 242 | } 243 | 244 | public static void lockScreen() { 245 | Context context = KissTools.getApplicationContext(); 246 | DevicePolicyManager deviceManager = (DevicePolicyManager) context 247 | .getSystemService(Context.DEVICE_POLICY_SERVICE); 248 | deviceManager.lockNow(); 249 | } 250 | 251 | // 252 | public final static void inputKeyEvent(int keyCode) { 253 | try { 254 | runRootCmd("input keyevent " + keyCode); 255 | } catch (Exception e) { 256 | e.printStackTrace(); 257 | } 258 | } 259 | 260 | public static String runCmd(String cmd) { 261 | if (TextUtils.isEmpty(cmd)) { 262 | return null; 263 | } 264 | Process process = null; 265 | String result = null; 266 | 267 | String[] commands = { "/system/bin/sh", "-c", cmd }; 268 | 269 | try { 270 | process = Runtime.getRuntime().exec(commands); 271 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 272 | int read = -1; 273 | InputStream errIs = process.getErrorStream(); 274 | while ((read = errIs.read()) != -1) { 275 | baos.write(read); 276 | } 277 | baos.write('\n'); 278 | 279 | InputStream inIs = process.getInputStream(); 280 | while ((read = inIs.read()) != -1) { 281 | baos.write(read); 282 | } 283 | 284 | byte[] data = baos.toByteArray(); 285 | result = new String(data); 286 | 287 | LogUtil.d(TAG, "runCmd result " + result); 288 | } catch (IOException e) { 289 | e.printStackTrace(); 290 | } 291 | return result; 292 | } 293 | 294 | public static String runRootCmd(String cmd) { 295 | if (TextUtils.isEmpty(cmd)) { 296 | return null; 297 | } 298 | 299 | Process process = null; 300 | String result = null; 301 | 302 | try { 303 | String[] commands = { "su", "-c", cmd }; 304 | process = Runtime.getRuntime().exec(commands); 305 | 306 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 307 | int read = -1; 308 | InputStream errIs = process.getErrorStream(); 309 | while ((read = errIs.read()) != -1) { 310 | baos.write(read); 311 | } 312 | baos.write('\n'); 313 | 314 | InputStream inIs = process.getInputStream(); 315 | while ((read = inIs.read()) != -1) { 316 | baos.write(read); 317 | } 318 | 319 | byte[] data = baos.toByteArray(); 320 | result = new String(data); 321 | 322 | LogUtil.d(TAG, "runRootCmd result " + result); 323 | } catch (IOException e) { 324 | e.printStackTrace(); 325 | } 326 | return result; 327 | } 328 | 329 | public static int getDistance(MotionEvent e1, MotionEvent e2) { 330 | float x = e1.getX() - e2.getX(); 331 | float y = e1.getY() - e2.getY(); 332 | return (int) Math.sqrt(x * x + y * y); 333 | } 334 | 335 | public static long getMaxMemory() { 336 | Runtime runtime = Runtime.getRuntime(); 337 | long maxMemory = runtime.maxMemory(); 338 | LogUtil.d(TAG, "application max memory " + maxMemory); 339 | return maxMemory; 340 | } 341 | 342 | public static void restartApplication(Class clazz) { 343 | Context context = KissTools.getApplicationContext(); 344 | Intent intent = new Intent(context, clazz); 345 | int pendingIntentId = 198964; 346 | PendingIntent pendingIntent = PendingIntent.getActivity(context, 347 | pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT); 348 | AlarmManager am = (AlarmManager) context 349 | .getSystemService(Context.ALARM_SERVICE); 350 | am.set(AlarmManager.RTC, System.currentTimeMillis() + 500, 351 | pendingIntent); 352 | System.exit(0); 353 | } 354 | 355 | public static void killApplication(String packageName) { 356 | try { 357 | Context context = KissTools.getApplicationContext(); 358 | ActivityManager activityManager = (ActivityManager) context 359 | .getSystemService(Context.ACTIVITY_SERVICE); 360 | activityManager.killBackgroundProcesses(packageName); 361 | Method forceStopPackage = activityManager.getClass() 362 | .getDeclaredMethod("forceStopPackage", String.class); 363 | forceStopPackage.setAccessible(true); 364 | forceStopPackage.invoke(activityManager, packageName); 365 | } catch (Exception e) { 366 | e.printStackTrace(); 367 | } 368 | } 369 | 370 | public static final boolean isMainThread() { 371 | return Looper.getMainLooper() == Looper.myLooper(); 372 | } 373 | 374 | public static void runOnMain(Runnable runnable) { 375 | if (runnable == null) { 376 | return; 377 | } 378 | 379 | if (isMainThread()) { 380 | runnable.run(); 381 | } else { 382 | Handler handler = new Handler(Looper.getMainLooper()); 383 | handler.post(runnable); 384 | } 385 | } 386 | 387 | public static void runOnMain(Runnable runnable, long delay) { 388 | if (runnable == null) { 389 | return; 390 | } 391 | Handler handler = new Handler(Looper.getMainLooper()); 392 | handler.postDelayed(runnable, delay); 393 | } 394 | 395 | @TargetApi(VERSION_CODES.KITKAT) 396 | public static void hideSystemUI(Activity activity) { 397 | View decorView = activity.getWindow().getDecorView(); 398 | decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE 399 | | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 400 | | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN 401 | | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION 402 | | View.SYSTEM_UI_FLAG_LOW_PROFILE 403 | | View.SYSTEM_UI_FLAG_FULLSCREEN 404 | | View.SYSTEM_UI_FLAG_IMMERSIVE); 405 | } 406 | 407 | @TargetApi(VERSION_CODES.KITKAT) 408 | public static void showSystemUI(Activity activity) { 409 | View decorView = activity.getWindow().getDecorView(); 410 | decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE 411 | | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 412 | | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); 413 | } 414 | } 415 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/TimeUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.text.ParseException; 12 | import java.text.SimpleDateFormat; 13 | import java.util.Date; 14 | 15 | import android.annotation.SuppressLint; 16 | import android.text.TextUtils; 17 | 18 | @SuppressLint("SimpleDateFormat") 19 | public class TimeUtil { 20 | public static final String TAG = "TimeUtil"; 21 | 22 | public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"; 23 | public static final String UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; 24 | public static final String FILE_FORMAT = "yyyy_MM_dd_HH_mm_ss_SSS"; 25 | 26 | public static long format(String time, String format) { 27 | if (TextUtils.isEmpty(time)) { 28 | return 0; 29 | } 30 | SimpleDateFormat sdf = new SimpleDateFormat(format); 31 | long modified = 0; 32 | try { 33 | Date date = sdf.parse(time); 34 | modified = date.getTime(); 35 | } catch (ParseException e) { 36 | e.printStackTrace(); 37 | } 38 | return modified; 39 | } 40 | 41 | public static String format(long time) { 42 | SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_FORMAT); 43 | Date date = new Date(time); 44 | return sdf.format(date); 45 | } 46 | 47 | public static String format(long time, String format) { 48 | SimpleDateFormat sdf = new SimpleDateFormat(format); 49 | Date date = new Date(time); 50 | return sdf.format(date); 51 | } 52 | 53 | public static String format(Date date, String format) { 54 | if (TextUtils.isEmpty(format) || date == null) { 55 | return null; 56 | } 57 | SimpleDateFormat sdf = new SimpleDateFormat(format); 58 | return sdf.format(date); 59 | } 60 | 61 | public static String format(String timeStr, String srcFormat, 62 | String dstFormat) { 63 | long time = format(timeStr, srcFormat); 64 | String result = format(time, dstFormat); 65 | return result; 66 | } 67 | 68 | public static String utcToLocal(String utcTime) { 69 | String localTime = null; 70 | try { 71 | SimpleDateFormat sdf = new SimpleDateFormat(UTC_FORMAT); 72 | Date date = sdf.parse(utcTime); 73 | sdf.applyPattern(DEFAULT_FORMAT); 74 | localTime = sdf.format(date); 75 | } catch (Exception e) { 76 | e.printStackTrace(); 77 | } 78 | return localTime; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/ToastUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import android.annotation.SuppressLint; 12 | import android.content.Context; 13 | import android.text.TextUtils; 14 | import android.widget.Toast; 15 | 16 | import com.kisstools.KissTools; 17 | 18 | public class ToastUtil { 19 | public static Toast mToast; 20 | 21 | @SuppressLint("ShowToast") 22 | private static void initToast() { 23 | if (mToast != null) { 24 | return; 25 | } 26 | Context context = KissTools.getApplicationContext(); 27 | if (context == null) { 28 | return; 29 | } 30 | mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT); 31 | } 32 | 33 | public static void show(int resId) { 34 | initToast(); 35 | if (resId < 0 || mToast == null) { 36 | return; 37 | } 38 | 39 | mToast.setText(resId); 40 | mToast.show(); 41 | } 42 | 43 | public static void show(String message) { 44 | initToast(); 45 | if (TextUtils.isEmpty(message) || mToast == null) { 46 | return; 47 | } 48 | 49 | mToast.setText(message); 50 | mToast.show(); 51 | } 52 | 53 | public static void dismiss() { 54 | if (mToast == null) { 55 | return; 56 | } 57 | mToast.cancel(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/UrlUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.net.URLEncoder; 12 | 13 | import android.net.Uri; 14 | import android.text.TextUtils; 15 | 16 | public class UrlUtil { 17 | public static final String TAG = "UrlUtil"; 18 | 19 | public static String encode(String url) { 20 | if (TextUtils.isEmpty(url)) { 21 | return url; 22 | } 23 | 24 | String encodedURL = ""; 25 | String[] temp = url.split("/"); 26 | int length = temp.length; 27 | for (int index = 0; index < length; index++) { 28 | try { 29 | temp[index] = URLEncoder.encode(temp[index], "UTF-8"); 30 | temp[index] = temp[index].replace("+", "%20"); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | return url; 34 | } 35 | encodedURL += temp[index]; 36 | if (index < (length - 1)) { 37 | encodedURL += "/"; 38 | } 39 | } 40 | return encodedURL; 41 | } 42 | 43 | public static Uri parse(String url) { 44 | if (TextUtils.isEmpty(url)) { 45 | return null; 46 | } 47 | 48 | Uri uri = null; 49 | try { 50 | uri = Uri.parse(url); 51 | } catch (Exception e) { 52 | 53 | } 54 | return uri; 55 | } 56 | 57 | public static String getParam(String url, String key) { 58 | Uri uri = parse(url); 59 | if (uri == null) { 60 | return null; 61 | } 62 | 63 | String value = null; 64 | try { 65 | value = uri.getQueryParameter(key); 66 | } catch (Exception e) { 67 | e.printStackTrace(); 68 | } 69 | return value; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/UserUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | public class UserUtil { 12 | public static final String TAG = "UserUtil"; 13 | 14 | private static String userId; 15 | 16 | public static final String getUserId() { 17 | return userId; 18 | } 19 | 20 | public static final void setUserId(String id) { 21 | userId = id; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/VerifyUtil.java: -------------------------------------------------------------------------------- 1 | package com.kisstools.utils; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.InputStream; 6 | import java.security.KeyFactory; 7 | import java.security.PublicKey; 8 | import java.security.Signature; 9 | import java.security.spec.X509EncodedKeySpec; 10 | 11 | import android.util.Base64; 12 | 13 | public class VerifyUtil { 14 | 15 | private static final int BUFFER_SIZE = 8192; 16 | 17 | private String signKey; 18 | private String signAlgorithm; 19 | private String keyAlgorithm; 20 | private String signature; 21 | 22 | public void setSignKey(String signKey) { 23 | this.signKey = signKey; 24 | } 25 | 26 | public void setSignAlgorithm(String sa) { 27 | this.signAlgorithm = sa; 28 | } 29 | 30 | public void setKeyAlgorithm(String ka) { 31 | this.keyAlgorithm = ka; 32 | } 33 | 34 | public void setSignature(String signature) { 35 | this.signature = signature; 36 | } 37 | 38 | public boolean verify(File file) { 39 | FileInputStream fis = null; 40 | try { 41 | fis = new FileInputStream(file); 42 | } catch (Exception e) { 43 | return false; 44 | } 45 | return verify(fis); 46 | } 47 | 48 | public boolean verify(InputStream is) { 49 | boolean verified = false; 50 | try { 51 | byte[] keyBytes = Base64.decode(signKey, Base64.NO_WRAP); 52 | X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); 53 | KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm); 54 | PublicKey publicKey = keyFactory.generatePublic(spec); 55 | 56 | Signature signer = Signature.getInstance(signAlgorithm); 57 | signer.initVerify(publicKey); 58 | 59 | byte[] buffer = new byte[BUFFER_SIZE]; 60 | int count; 61 | while ((count = is.read(buffer)) > 0) { 62 | signer.update(buffer, 0, count); 63 | } 64 | is.close(); 65 | 66 | byte[] signatureBytes = Base64.decode(signature, Base64.NO_WRAP); 67 | verified = signer.verify(signatureBytes); 68 | } catch (Exception e) { 69 | e.printStackTrace(); 70 | } 71 | return verified; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/ViewUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.lang.reflect.Method; 12 | 13 | import android.annotation.SuppressLint; 14 | import android.graphics.Bitmap; 15 | import android.graphics.Point; 16 | import android.graphics.Rect; 17 | import android.os.Build; 18 | import android.text.TextPaint; 19 | import android.text.TextUtils; 20 | import android.view.MotionEvent; 21 | import android.view.View; 22 | import android.view.ViewGroup; 23 | import android.view.ViewParent; 24 | import android.view.animation.AlphaAnimation; 25 | import android.widget.TextView; 26 | 27 | public class ViewUtil { 28 | public static final String TAG = "ViewUtil"; 29 | 30 | public final static int measureTextWidth(TextView view, String text) { 31 | if (TextUtils.isEmpty(text)) { 32 | return 0; 33 | } 34 | 35 | TextPaint paint = view.getPaint(); 36 | int width = (int) paint.measureText(text); 37 | return width; 38 | } 39 | 40 | public static boolean eventInView(MotionEvent event, View view) { 41 | if (event == null || view == null) { 42 | return false; 43 | } 44 | 45 | int eventX = (int) event.getRawX(); 46 | int eventY = (int) event.getRawY(); 47 | 48 | int[] location = new int[2]; 49 | view.getLocationOnScreen(location); 50 | 51 | int width = view.getWidth(); 52 | int height = view.getHeight(); 53 | int left = location[0]; 54 | int top = location[1]; 55 | int right = left + width; 56 | int bottom = top + height; 57 | 58 | Rect rect = new Rect(left, top, right, bottom); 59 | boolean contains = rect.contains(eventX, eventY); 60 | return contains; 61 | } 62 | 63 | public static Point getViewCenter(View view) { 64 | if (view == null) { 65 | return new Point(); 66 | } 67 | 68 | int[] location = new int[2]; 69 | view.getLocationOnScreen(location); 70 | int x = location[0] + view.getWidth() / 2; 71 | int y = location[1] + view.getHeight() / 2; 72 | return new Point(x, y); 73 | } 74 | 75 | @SuppressLint("NewApi") 76 | public static void setAlpha(View view, float alpha) { 77 | if (Build.VERSION.SDK_INT < 11) { 78 | final AlphaAnimation animation = new AlphaAnimation(alpha, alpha); 79 | animation.setDuration(0); 80 | animation.setFillAfter(true); 81 | view.startAnimation(animation); 82 | } else { 83 | view.setAlpha(alpha); 84 | } 85 | } 86 | 87 | public static void removeFromParent(View view) { 88 | if (view == null) { 89 | return; 90 | } 91 | 92 | ViewParent parent = view.getParent(); 93 | if (parent instanceof ViewGroup) { 94 | ((ViewGroup) parent).removeView(view); 95 | } 96 | } 97 | 98 | public static Bitmap capture(View view) { 99 | if (view == null) { 100 | return null; 101 | } 102 | boolean oldEnabled = view.isDrawingCacheEnabled(); 103 | view.setDrawingCacheEnabled(true); 104 | view.buildDrawingCache(); 105 | Bitmap bitmap = view.getDrawingCache(); 106 | if (!oldEnabled) { 107 | view.setDrawingCacheEnabled(false); 108 | } 109 | return bitmap; 110 | } 111 | 112 | public static void toggleSoftInput(TextView tv, boolean enable) { 113 | Method setShowSoftInputOnFocus = null; 114 | try { 115 | Method[] methods = tv.getClass().getMethods(); 116 | for (Method m : methods) { 117 | String name = m.getName(); 118 | if (name.equals("setSoftInputShownOnFocus")) { 119 | setShowSoftInputOnFocus = tv.getClass().getMethod( 120 | "setSoftInputShownOnFocus", boolean.class); 121 | break; 122 | } else if (name.equals("setShowSoftInputOnFocus")) { 123 | setShowSoftInputOnFocus = tv.getClass().getMethod( 124 | "setShowSoftInputOnFocus", boolean.class); 125 | break; 126 | } 127 | } 128 | if (null != setShowSoftInputOnFocus) { 129 | setShowSoftInputOnFocus.setAccessible(true); 130 | setShowSoftInputOnFocus.invoke(tv, enable); 131 | } 132 | } catch (Exception e) { 133 | e.printStackTrace(); 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/com/kisstools/utils/ZipUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * Copyright (c) 2014 CoderKiss 4 | * 5 | * CoderKiss[AT]gmail.com 6 | * 7 | */ 8 | 9 | package com.kisstools.utils; 10 | 11 | import java.io.BufferedInputStream; 12 | import java.io.BufferedOutputStream; 13 | import java.io.File; 14 | import java.io.FileInputStream; 15 | import java.io.FileOutputStream; 16 | import java.io.IOException; 17 | import java.util.zip.ZipEntry; 18 | import java.util.zip.ZipInputStream; 19 | import java.util.zip.ZipOutputStream; 20 | 21 | import android.util.Log; 22 | 23 | public class ZipUtil { 24 | public static final String TAG = "ZipUtil"; 25 | 26 | private final static int BUFFER_SIZE = 8192; 27 | 28 | public static boolean zip(String filePath, String zipPath) { 29 | try { 30 | File file = new File(filePath); 31 | BufferedInputStream bis = null; 32 | FileOutputStream fos = new FileOutputStream(zipPath); 33 | ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream( 34 | fos)); 35 | if (file.isDirectory()) { 36 | int baseLength = file.getParent().length() + 1; 37 | zipFolder(zos, file, baseLength); 38 | } else { 39 | byte data[] = new byte[BUFFER_SIZE]; 40 | FileInputStream fis = new FileInputStream(filePath); 41 | bis = new BufferedInputStream(fis, BUFFER_SIZE); 42 | String entryName = file.getName(); 43 | Log.i(TAG, "zip entry " + entryName); 44 | ZipEntry entry = new ZipEntry(entryName); 45 | zos.putNextEntry(entry); 46 | int count; 47 | while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) { 48 | zos.write(data, 0, count); 49 | } 50 | } 51 | zos.close(); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | return false; 55 | } 56 | return true; 57 | } 58 | 59 | private static void zipFolder(ZipOutputStream zos, File folder, 60 | int baseLength) throws IOException { 61 | if (zos == null || folder == null) { 62 | return; 63 | } 64 | File[] fileList = folder.listFiles(); 65 | 66 | if (fileList == null || fileList.length == 0) { 67 | return; 68 | } 69 | 70 | for (File file : fileList) { 71 | if (file.isDirectory()) { 72 | zipFolder(zos, file, baseLength); 73 | } else { 74 | byte data[] = new byte[BUFFER_SIZE]; 75 | String unmodifiedFilePath = file.getPath(); 76 | String realPath = unmodifiedFilePath.substring(baseLength); 77 | Log.i(TAG, "zip entry " + realPath); 78 | FileInputStream fi = new FileInputStream(unmodifiedFilePath); 79 | BufferedInputStream bis = new BufferedInputStream(fi, 80 | BUFFER_SIZE); 81 | ZipEntry entry = new ZipEntry(realPath); 82 | zos.putNextEntry(entry); 83 | int count; 84 | while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) { 85 | zos.write(data, 0, count); 86 | } 87 | bis.close(); 88 | } 89 | } 90 | } 91 | 92 | public static boolean unzip(String zipPath, String unzipFolder) { 93 | if (!FileUtil.exists(zipPath)) { 94 | LogUtil.e(TAG, "zip path not exists!"); 95 | return false; 96 | } 97 | 98 | if (!FileUtil.mkdirs(unzipFolder, true)) { 99 | LogUtil.e(TAG, "failed to create unzip folder."); 100 | return false; 101 | } 102 | 103 | try { 104 | FileInputStream fin = new FileInputStream(zipPath); 105 | ZipInputStream zin = new ZipInputStream(fin); 106 | ZipEntry ze = null; 107 | while ((ze = zin.getNextEntry()) != null) { 108 | String entryName = ze.getName(); 109 | LogUtil.d(TAG, "unzip entry " + entryName); 110 | 111 | String entryPath = unzipFolder + "/" + entryName; 112 | if (ze.isDirectory()) { 113 | FileUtil.mkdirs(entryPath); 114 | } else { 115 | if (!FileUtil.create(entryPath, true)) { 116 | continue; 117 | } 118 | FileOutputStream fout = new FileOutputStream(entryPath); 119 | byte[] buffer = new byte[BUFFER_SIZE]; 120 | int len; 121 | while ((len = zin.read(buffer)) != -1) { 122 | fout.write(buffer, 0, len); 123 | } 124 | fout.close(); 125 | zin.closeEntry(); 126 | } 127 | } 128 | zin.close(); 129 | } catch (Exception e) { 130 | LogUtil.e("unzip exception", e); 131 | return false; 132 | } 133 | return true; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/com/kisstools/view/FullscreenView.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author dawson dong 3 | */ 4 | 5 | package com.kisstools.view; 6 | 7 | import android.annotation.TargetApi; 8 | import android.app.Activity; 9 | import android.content.Context; 10 | import android.os.Build; 11 | import android.util.AttributeSet; 12 | import android.util.Log; 13 | import android.view.View; 14 | import android.view.View.OnSystemUiVisibilityChangeListener; 15 | import android.widget.LinearLayout; 16 | import android.widget.TextView; 17 | 18 | import com.kisstools.utils.SystemUtil; 19 | 20 | @TargetApi(Build.VERSION_CODES.HONEYCOMB) 21 | public class FullscreenView extends LinearLayout implements 22 | OnSystemUiVisibilityChangeListener { 23 | 24 | public static final String TAG = "FullscreenView"; 25 | 26 | private View decorView; 27 | private View paddingView; 28 | private TextView tvTitleBar; 29 | 30 | public FullscreenView(Context context, AttributeSet attrs) { 31 | super(context, attrs); 32 | Activity activity = (Activity) getContext(); 33 | decorView = activity.getWindow().getDecorView(); 34 | } 35 | 36 | protected void onFinishInflate() { 37 | super.onFinishInflate(); 38 | paddingView = new TextView(getContext()); 39 | paddingView.setVisibility(View.GONE); 40 | this.setOrientation(VERTICAL); 41 | int height = SystemUtil.getStatusBarHeight(getContext()); 42 | LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, 43 | height); 44 | this.addView(paddingView, 0, params); 45 | tvTitleBar = new TextView(getContext()); 46 | tvTitleBar.setText("TitleBar"); 47 | tvTitleBar.setBackgroundColor(0xB0444444); 48 | height = SystemUtil.getActionBarHeight(getContext()); 49 | params = new LayoutParams(LayoutParams.MATCH_PARENT, height); 50 | this.addView(tvTitleBar, 1, params); 51 | } 52 | 53 | @Override 54 | protected void onAttachedToWindow() { 55 | super.onAttachedToWindow(); 56 | setOnSystemUiVisibilityChangeListener(this); 57 | } 58 | 59 | @Override 60 | protected void onDetachedFromWindow() { 61 | super.onDetachedFromWindow(); 62 | } 63 | 64 | public void enableFullscreen() { 65 | paddingView.setVisibility(View.VISIBLE); 66 | 67 | int visibility = 0; 68 | visibility |= SYSTEM_UI_FLAG_LOW_PROFILE; 69 | visibility |= SYSTEM_UI_FLAG_HIDE_NAVIGATION; 70 | visibility |= SYSTEM_UI_FLAG_FULLSCREEN; 71 | visibility |= SYSTEM_UI_FLAG_LAYOUT_STABLE; 72 | visibility |= SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; 73 | visibility |= SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 74 | 75 | decorView.setSystemUiVisibility(visibility); 76 | } 77 | 78 | @Override 79 | public void onSystemUiVisibilityChange(int visibility) { 80 | Log.d(TAG, "onSystemUiVisibilityChange " + visibility); 81 | boolean fullscreen = (visibility & SYSTEM_UI_FLAG_LOW_PROFILE) != 0; 82 | tvTitleBar.setVisibility(fullscreen ? View.INVISIBLE : View.VISIBLE); 83 | } 84 | } 85 | --------------------------------------------------------------------------------