Last active
October 29, 2015 09:57
-
-
Save likangwei/d6a5f546785431b28b2f to your computer and use it in GitHub Desktop.
Android Utils
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import android.annotation.SuppressLint; | |
import android.app.DownloadManager; | |
import android.content.Context; | |
import android.content.pm.PackageManager.NameNotFoundException; | |
import android.os.Environment; | |
import android.util.Log; | |
@SuppressLint("NewApi") | |
public class AppOnlineUpdate { | |
private final static String TAG = "AppOnlineUpdate"; | |
// version json url | |
private final static String VERURL = "http://mloader.sinaapp.com/NFC_Flower_version.html"; | |
// apk download directory | |
private final static String DOWNLOADDIR = Environment.DIRECTORY_DOWNLOADS; | |
// apk name | |
private final static String APKNAME = "QRToken.apk"; | |
// apk download url | |
private static String APKURL = ""; | |
private Context mContext; | |
private String curVerName; | |
private String newVerName = "1.0"; | |
private int curVerCode; | |
private int newVerCode = 1; | |
private long dmID; | |
private DownloadManager dm; | |
// --Commented out by Inspection START (2015/3/4 11:58): | |
// public AppOnlineUpdate(Context mContext) { | |
// this.mContext = mContext; | |
// curVerName = getVerName(mContext); | |
// curVerCode = getVerCode(mContext); | |
// dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE); | |
// APKURL = GetDownload_URL.getDownload_URL(mContext); | |
// } | |
// --Commented out by Inspection STOP (2015/3/4 11:58) | |
private static int getVerCode(Context context) { | |
int verCode = -1; | |
try { | |
verCode = | |
context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; | |
} catch (NameNotFoundException e) { | |
Log.e(TAG, e.getMessage()); | |
} | |
return verCode; | |
} | |
private static String getVerName(Context context) { | |
String verName = ""; | |
try { | |
verName = | |
context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; | |
} catch (NameNotFoundException e) { | |
Log.e(TAG, e.getMessage()); | |
} | |
return verName; | |
} | |
private String getURLResponse(String urlString) { | |
HttpURLConnection conn = null; | |
InputStream is = null; | |
String resultData = ""; | |
try { | |
URL url = new URL(urlString); | |
conn = (HttpURLConnection) url.openConnection(); | |
conn.setDoInput(true); | |
conn.setDoOutput(true); | |
conn.setUseCaches(false); | |
conn.setRequestMethod("GET"); | |
conn.setConnectTimeout(5000); | |
conn.setReadTimeout(5000); | |
is = conn.getInputStream(); | |
InputStreamReader isr = new InputStreamReader(is); | |
BufferedReader bufferReader = new BufferedReader(isr); | |
String inputLine = null; | |
while ((inputLine = bufferReader.readLine()) != null) { | |
resultData += inputLine + "\n"; | |
} | |
} catch (MalformedURLException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
if (is != null) { | |
try { | |
is.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
if (conn != null) { | |
conn.disconnect(); | |
} | |
} | |
return resultData; | |
} | |
private boolean parseJson(String data) throws JSONException { | |
if (!data.equals("")) { | |
// Log.d(TAG, "data" + data); | |
String verjson = data; | |
JSONArray array = new JSONArray(verjson); | |
if (array.length() > 0) { | |
JSONObject obj = array.getJSONObject(0); | |
try { | |
newVerCode = Integer.parseInt(obj.getString("verCode")); | |
newVerName = obj.getString("verName"); | |
} catch (Exception e) { | |
newVerCode = 1; | |
newVerName = "1.0"; | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
private void deleteOldFile() { | |
File file = new File(Environment.getExternalStoragePublicDirectory(DOWNLOADDIR), APKNAME); | |
if (file.exists()) | |
file.delete(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.pm.ApplicationInfo; | |
import android.content.pm.PackageInfo; | |
import android.content.pm.PackageManager; | |
import android.content.pm.PackageManager.NameNotFoundException; | |
import android.net.Uri; | |
import android.telephony.TelephonyManager; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
public class AppUtils { | |
/** | |
* @param c | |
* @param pkgName | |
* @return 如果存在此应用,则返回app verion name,如果没有则返回null | |
*/ | |
public static PackageInfo getPkgInfo(Context c, String pkgName) { | |
PackageManager pkgManager = c.getPackageManager(); | |
try { | |
PackageInfo pkgInfo = pkgManager.getPackageInfo(pkgName, PackageManager.GET_UNINSTALLED_PACKAGES); | |
return pkgInfo; | |
} catch (NameNotFoundException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
public static String getVersionNameByPkgName(Context c, String pkgName) { | |
PackageManager pkgManager = c.getPackageManager(); | |
try { | |
PackageInfo pkgInfo = pkgManager.getPackageInfo(pkgName, PackageManager.GET_UNINSTALLED_PACKAGES); | |
return pkgInfo.versionName; | |
} catch (NameNotFoundException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
public static int getVersionCode(Context c, String pkgName){ | |
PackageManager pkgManager = c.getPackageManager(); | |
try { | |
PackageInfo pkgInfo = pkgManager.getPackageInfo(pkgName, PackageManager.GET_UNINSTALLED_PACKAGES); | |
return pkgInfo.versionCode; | |
} catch (NameNotFoundException e) { | |
e.printStackTrace(); | |
} | |
return 0; | |
} | |
/** | |
* 获取应用程序名称 | |
*/ | |
public static String getAppNameByPkgName(Context ctx, String pkgName) { | |
PackageManager pm = ctx.getPackageManager(); | |
String name = null; | |
try { | |
name = pm.getApplicationLabel(pm.getApplicationInfo(pkgName, | |
PackageManager.GET_META_DATA)).toString(); | |
} catch (NameNotFoundException e) { | |
e.printStackTrace(); | |
} | |
return name; | |
} | |
public static String getDeviceId(Context ctx) { | |
TelephonyManager TelephonyMgr = (TelephonyManager)ctx.getSystemService(Context.TELEPHONY_SERVICE); | |
String szImei = TelephonyMgr.getDeviceId(); | |
return szImei; | |
} | |
public static String getBuildTime(Context ctx){ | |
String buildTime = null; | |
try { | |
InputStream ips = ctx.getAssets().open("build.txt"); | |
byte[] bts = new byte[1024]; | |
int len = ips.read(bts); | |
buildTime = new String(bts, 0, len, "GBK"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
buildTime = "编译时间 :" + buildTime; | |
return buildTime; | |
} | |
public static void sendLog2QQ(Context ctx, String log){ | |
Intent itn = new Intent(android.content.Intent.ACTION_SEND); | |
itn.setType("*/*"); | |
File logFile = MyLog.getLogFile(true); | |
MyLog.i(logFile.getAbsolutePath()); | |
if(logFile == null && !logFile.canWrite()){ | |
MyToast.show(ctx, "log文件生成失败"); | |
return; | |
} | |
try { | |
FileWriter writer = new FileWriter(logFile.getAbsolutePath(), true); | |
writer.write(log); | |
writer.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
itn.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logFile)); | |
ctx.startActivity(itn); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
public class Crc8Util { | |
static byte[] crc8_tab = {(byte) 0, (byte) 94, (byte) 188, (byte) 226, (byte) 97, (byte) 63, (byte) 221, (byte) 131, (byte) 194, (byte) 156, (byte) 126, (byte) 32, (byte) 163, (byte) 253, (byte) 31, (byte) 65, (byte) 157, (byte) 195, (byte) 33, (byte) 127, (byte) 252, (byte) 162, (byte) 64, (byte) 30, (byte) 95, (byte) 1, (byte) 227, (byte) 189, (byte) 62, (byte) 96, (byte) 130, (byte) 220, (byte) 35, (byte) 125, (byte) 159, (byte) 193, (byte) 66, (byte) 28, (byte) 254, (byte) 160, (byte) 225, (byte) 191, (byte) 93, (byte) 3, (byte) 128, (byte) 222, (byte) 60, (byte) 98, (byte) 190, (byte) 224, (byte) 2, (byte) 92, (byte) 223, (byte) 129, (byte) 99, (byte) 61, (byte) 124, (byte) 34, (byte) 192, (byte) 158, (byte) 29, (byte) 67, (byte) 161, (byte) 255, (byte) 70, (byte) 24, | |
(byte) 250, (byte) 164, (byte) 39, (byte) 121, (byte) 155, (byte) 197, (byte) 132, (byte) 218, (byte) 56, (byte) 102, (byte) 229, (byte) 187, (byte) 89, (byte) 7, (byte) 219, (byte) 133, (byte) 103, (byte) 57, (byte) 186, (byte) 228, (byte) 6, (byte) 88, (byte) 25, (byte) 71, (byte) 165, (byte) 251, (byte) 120, (byte) 38, (byte) 196, (byte) 154, (byte) 101, (byte) 59, (byte) 217, (byte) 135, (byte) 4, (byte) 90, (byte) 184, (byte) 230, (byte) 167, (byte) 249, (byte) 27, (byte) 69, (byte) 198, (byte) 152, (byte) 122, (byte) 36, (byte) 248, (byte) 166, (byte) 68, (byte) 26, (byte) 153, (byte) 199, (byte) 37, (byte) 123, (byte) 58, (byte) 100, (byte) 134, (byte) 216, (byte) 91, (byte) 5, (byte) 231, (byte) 185, (byte) 140, (byte) 210, (byte) 48, (byte) 110, (byte) 237, | |
(byte) 179, (byte) 81, (byte) 15, (byte) 78, (byte) 16, (byte) 242, (byte) 172, (byte) 47, (byte) 113, (byte) 147, (byte) 205, (byte) 17, (byte) 79, (byte) 173, (byte) 243, (byte) 112, (byte) 46, (byte) 204, (byte) 146, (byte) 211, (byte) 141, (byte) 111, (byte) 49, (byte) 178, (byte) 236, (byte) 14, (byte) 80, (byte) 175, (byte) 241, (byte) 19, (byte) 77, (byte) 206, (byte) 144, (byte) 114, (byte) 44, (byte) 109, (byte) 51, (byte) 209, (byte) 143, (byte) 12, (byte) 82, (byte) 176, (byte) 238, (byte) 50, (byte) 108, (byte) 142, (byte) 208, (byte) 83, (byte) 13, (byte) 239, (byte) 177, (byte) 240, (byte) 174, (byte) 76, (byte) 18, (byte) 145, (byte) 207, (byte) 45, (byte) 115, (byte) 202, (byte) 148, (byte) 118, (byte) 40, (byte) 171, (byte) 245, (byte) 23, (byte) 73, (byte) 8, | |
(byte) 86, (byte) 180, (byte) 234, (byte) 105, (byte) 55, (byte) 213, (byte) 139, (byte) 87, (byte) 9, (byte) 235, (byte) 181, (byte) 54, (byte) 104, (byte) 138, (byte) 212, (byte) 149, (byte) 203, (byte) 41, (byte) 119, (byte) 244, (byte) 170, (byte) 72, (byte) 22, (byte) 233, (byte) 183, (byte) 85, (byte) 11, (byte) 136, (byte) 214, (byte) 52, (byte) 106, (byte) 43, (byte) 117, (byte) 151, (byte) 201, (byte) 74, (byte) 20, (byte) 246, (byte) 168, (byte) 116, (byte) 42, (byte) 200, (byte) 150, (byte) 21, (byte) 75, (byte) 169, (byte) 247, (byte) 182, (byte) 232, (byte) 10, (byte) 84, (byte) 215, (byte) 137, (byte) 107, 53}; | |
/** | |
* 计算数组的CRC8校验值 | |
* | |
* @param data 需要计算的数组 | |
* @return CRC8校验值 | |
*/ | |
public static byte calcCrc8(byte[] data) { | |
return calcCrc8(data, 0, data.length, (byte) 0); | |
} | |
/** | |
* 计算CRC8校验值 | |
* | |
* @param data 数据 | |
* @param offset 起始位置 | |
* @param len 长度 | |
* @param preval 之前的校验值 | |
* @return 校验值 | |
*/ | |
public static byte calcCrc8(byte[] data, int offset, int len, byte preval) { | |
byte ret = preval; | |
for (int i = offset; i < (offset + len); ++i) { | |
ret = crc8_tab[(0x00ff & (ret ^ data[i]))]; | |
} | |
return ret; | |
} | |
public static String getCrc8Code(String source){ | |
String crc8Real = Integer.toHexString(Crc8Util.calcCrc8(source.getBytes())); | |
int strLen = crc8Real.length(); | |
if (strLen == 8) { | |
crc8Real = crc8Real.replace("ffffff", ""); | |
} else if (strLen == 1) { | |
crc8Real = "0" + crc8Real; | |
} | |
return crc8Real; | |
} | |
public static void main(String[] args){ | |
String phy = "100000001460000132847505411LA4FETUK6kv7m5OWBZeu1TttzLrG3upOMrovWV4b7/x1oaykdpmwKKTXQeChbw487Cxwj27PCPOLqiwwDCx9cAd9"; | |
String crcSource = phy.substring(0, phy.length()-2); | |
String crc8 = getCrc8Code(crcSource); | |
System.out.println(crc8); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils;/* * 文 件 名: DataCleanManager.java * 描 述: 主要功能有清除内/外缓存,清除数据库,清除sharedPreference,清除files和清除自定义目录 */ | |
import java.io.File; | |
import android.content.Context; | |
import android.os.Environment; | |
/** | |
* 本应用数据清除管理器 | |
*/ | |
public class DataCleanManager { | |
/** | |
* 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * * @param context | |
*/ | |
public static void cleanInternalCache(Context context) { | |
deleteFilesByDirectory(context.getCacheDir()); | |
} | |
/** | |
* 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * * @param context | |
*/ | |
public static void cleanDatabases(Context context) { | |
deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/databases")); | |
} | |
/** | |
* * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param | |
* context | |
*/ | |
public static void cleanSharedPreference(Context context) { | |
deleteFilesByDirectory(new File("/data/data/" | |
+ context.getPackageName() + "/shared_prefs")); | |
} | |
// --Commented out by Inspection START (2015/3/4 11:58): | |
// /** | |
// * 按名字清除本应用数据库 * * @param context * @param dbName | |
// */ | |
// public static void cleanDatabaseByName(Context context, String dbName) { | |
// context.deleteDatabase(dbName); | |
// } | |
// --Commented out by Inspection STOP (2015/3/4 11:58) | |
/** | |
* 清除/data/data/com.xxx.xxx/files下的内容 * * @param context | |
*/ | |
public static void cleanFiles(Context context) { | |
deleteFilesByDirectory(context.getFilesDir()); | |
} | |
/** | |
* * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param | |
* context | |
*/ | |
public static void cleanExternalCache(Context context) { | |
if (Environment.getExternalStorageState().equals( | |
Environment.MEDIA_MOUNTED)) { | |
deleteFilesByDirectory(context.getExternalCacheDir()); | |
} | |
} | |
/** | |
* 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * * @param filePath | |
*/ | |
public static void cleanCustomCache(String filePath) { | |
deleteFilesByDirectory(new File(filePath)); | |
} | |
/** | |
* 清除本应用所有的数据 * * @param context * @param filepath | |
*/ | |
public static void cleanApplicationData(Context context, String... filepath) { | |
cleanInternalCache(context); | |
cleanExternalCache(context); | |
cleanDatabases(context); | |
cleanSharedPreference(context); | |
cleanFiles(context); | |
for (String filePath : filepath) { | |
cleanCustomCache(filePath); | |
} | |
} | |
/** | |
* 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * * @param directory | |
*/ | |
private static void deleteFilesByDirectory(File directory) { | |
if (directory != null && directory.exists() && directory.isDirectory()) { | |
for (File item : directory.listFiles()) { | |
item.delete(); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.app.AlertDialog; | |
import android.app.Dialog; | |
import android.content.Context; | |
import android.content.DialogInterface; | |
import android.widget.Toast; | |
import com.stonete.qrtoken.activity.Homepage; | |
import com.stonete.qrtoken.dialog.My_Dialog; | |
/** | |
* Created by kangwei on 2015/2/28. | |
*/ | |
public class DialogUtils { | |
// 自定义单一按钮对话框 | |
public static My_Dialog showDialog(final Context ctx, final String message) { | |
MyLog.i(message); | |
My_Dialog.Builder builder = new My_Dialog.Builder(ctx); | |
builder.setMessage(message); | |
builder.setPositiveButton("确 定", | |
new DialogInterface.OnClickListener() { | |
public void onClick(DialogInterface dialog, int which) { | |
if (ctx instanceof Homepage) { | |
((Homepage) ctx).restartScan(); | |
} | |
} | |
}); | |
builder.setCancelable(false); | |
builder.create().show(); | |
return builder.create(); | |
} | |
public static My_Dialog showDialog(final Context ctx, final String message, final DialogInterface.OnClickListener listener) { | |
MyLog.i(message); | |
My_Dialog.Builder builder = new My_Dialog.Builder(ctx); | |
builder.setMessage(message); | |
builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { | |
public void onClick(DialogInterface dialog, int which) { | |
if(ctx instanceof Homepage){ | |
((Homepage) ctx).restartScan(); | |
} | |
if(listener != null){ | |
listener.onClick(dialog, which); | |
} | |
} | |
}); | |
builder.setCancelable(false); | |
builder.create().show(); | |
return builder.create(); | |
} | |
public static AlertDialog showDialog(final Context ctx, final String message, DialogInterface.OnClickListener listener, DialogInterface.OnClickListener cancelListener) { | |
AlertDialog.Builder builder = new AlertDialog.Builder(ctx); | |
builder.setMessage(message) | |
.setCancelable(false) | |
.setPositiveButton("Yes", listener) | |
.setNegativeButton("No", cancelListener); | |
AlertDialog alert = builder.create(); | |
alert.show(); | |
return alert; | |
} | |
public static void showToast(final Context ctx, final String message){ | |
Toast.makeText(ctx,message,Toast.LENGTH_SHORT).show(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.content.Context; | |
import android.os.Environment; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.security.interfaces.RSAPrivateKey; | |
/** | |
* Created by kangwei on 2015/3/19. | |
*/ | |
public class FileUtils { | |
public static String getCatchPath(Context ctx){ | |
File f = ctx.getExternalCacheDir(); | |
if (f != null) | |
{ | |
return f.getAbsolutePath(); | |
} | |
return null; | |
} | |
public static String getSDPath(){ | |
File sdDir = null; | |
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在 | |
if (sdCardExist) | |
{ | |
sdDir = Environment.getExternalStorageDirectory();//获取跟目录 | |
return sdDir.toString(); | |
} | |
return null; | |
} | |
public static byte[] readBytes(File f) { | |
if(f.exists() && f.canRead()){ | |
int len = (int) f.length(); | |
byte[] bts = new byte[len]; | |
try { | |
FileInputStream fips = new FileInputStream(f); | |
fips.read(bts); | |
fips.close(); | |
return bts; | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return null; | |
} | |
public static byte[] readBytes(String f) { | |
return readBytes(new File(f)); | |
} | |
public static boolean writeByte2File(byte[] encoded, String fileName) { | |
File file = new File(fileName); | |
try { | |
FileOutputStream fops = new FileOutputStream(file); | |
fops.write(encoded); | |
fops.close(); | |
return true; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return false; | |
} | |
} | |
public static String read(String s) { | |
byte[] bts = readBytes(new File(s)); | |
if(bts == null){ | |
return null; | |
} | |
return new String(bts); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
git status | |
git push |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import com.stonete.qrtoken.statics.StaticUtil; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.HttpClient; | |
import org.apache.http.client.entity.UrlEncodedFormEntity; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.client.methods.HttpPost; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.message.BasicNameValuePair; | |
import org.apache.http.params.CoreConnectionPNames; | |
import org.apache.http.util.EntityUtils; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Map; | |
public class HttpUtil { | |
/** | |
* @param url 发送请求的URL | |
* @param rawParams 请求参数 | |
* @return 服务器响应字符串 | |
* @throws Exception | |
*/ | |
private static HttpResponse postRequest(final String url, final Map<String, String> rawParams) { | |
HttpClient httpClient = new DefaultHttpClient(); | |
String result = null; | |
if(url == null){ | |
throw new RuntimeException("url == null"); | |
} | |
try { | |
HttpPost post = new HttpPost(url); | |
// 如果传递参数个数比较多的话可以对传递的参数进行封装 | |
List<NameValuePair> params = new ArrayList<NameValuePair>(); | |
for (String key : rawParams.keySet()) { | |
// 封装请求参数 | |
params.add(new BasicNameValuePair(key, rawParams.get(key))); | |
} | |
// 设置请求参数 | |
post.setEntity(new UrlEncodedFormEntity(params, "utf-8")); | |
// 设置请求头 | |
post.setHeader("content-type", "application/x-www-form-urlencoded; charset=utf-8"); | |
// 请求超时 | |
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); | |
// 读取超时 | |
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); | |
// 发送POST请求 | |
HttpResponse httpResponse = httpClient.execute(post); | |
// 如果服务器成功地返回响应 | |
return httpResponse; | |
} catch (Exception e) { | |
} | |
return null; | |
} | |
public static HttpUtilJsonResponse doHttpPostAndJsonValidCheck(final String url, final Map<String, String> rawParams) { | |
if(rawParams != null){ | |
rawParams.put("app_pf", "1"); | |
} | |
HttpUtilJsonResponse result = new HttpUtilJsonResponse(); | |
result.requestAndResponseBuffer.append("HTTP===START=======================\n"); | |
result.requestAndResponseBuffer.append("HTTP=url=>" + url+"\n"); | |
result.requestAndResponseBuffer.append("HTTP=REQUEST=>" + rawParams + "\n"); | |
result.url = url; | |
if(MyLog.DEBUG){ | |
result.e = requestParamCheck(url, rawParams); | |
} | |
//验证request 参数是否正确 | |
if (result.isError()) { | |
//request 参数验证失败 | |
return result; | |
} else { | |
//request 参数验证成功,进行http请求 | |
HttpResponse httpResponse = postRequest(url, rawParams); | |
if (httpResponse == null) { | |
//请求数据失败 | |
result.e = new IError(); | |
result.e.errorMsg = "网络异常,请重试"; | |
} else if (httpResponse.getStatusLine().getStatusCode() != 200) { | |
// 获取服务器响应字符串 | |
result.e = new IError(); | |
try { | |
result.e.errorMsg = "网络异常,请重试。 error:" + httpResponse.getStatusLine().getStatusCode(); | |
result.e.errorCode = httpResponse.getStatusLine().getStatusCode(); | |
if(MyLog.DEBUG){ | |
String lines = EntityUtils.toString(httpResponse.getEntity()); | |
result.e.errorMsg = result.e.errorMsg + lines; | |
MyLog.e(lines); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}else { | |
//请求数据成功 | |
String scanResultStr = null; | |
try { | |
scanResultStr = EntityUtils.toString(httpResponse.getEntity()); | |
result.requestAndResponseBuffer.append("HTTP=RESPONSE=>" + scanResultStr+"\n"); | |
result.requestAndResponseBuffer.append("HTTP_END--------------------------\n"); | |
JSONObject resultJson = new JSONObject(scanResultStr); | |
result.jo = resultJson; | |
IError responseParamCheck = responseParamCheck(url, rawParams, resultJson); | |
result.e = responseParamCheck; | |
if (!resultJson.isNull("ret")) { | |
result.ret = resultJson.getString("ret"); | |
} | |
} catch (JSONException e) { | |
result.e = new IError(); | |
result.e.errorMsg = "HTTP ERROR Response is not json error==>" + url + "\nparams==>" + rawParams + "\nresponse==>" + scanResultStr; | |
} catch (Exception e) { | |
result.e = new IError(); | |
result.e.errorMsg = "HTTP ERROR Response unKnow error==>" + url + "\nparams==>" + rawParams + "\nresponse==>" + scanResultStr + e.getLocalizedMessage(); | |
e.printStackTrace(); | |
} | |
} | |
} | |
if(result.isError()){ | |
result.requestAndResponseBuffer.append(result.e.errorMsg); | |
} | |
MyLog.i(result.getRequestAndResponse()); | |
return result; | |
} | |
public static IError requestParamCheck(String url, final Map<String, String> requestParams) { | |
//判断请求参数是否正确,如果正确,返回null | |
if(url == null){ | |
IError e = new IError(); | |
e.errorMsg = "HTTP REQUEST ERROR==>您请求了一个空的url"; | |
return e; | |
} | |
for (int i = 0; i < StaticUtil.url_param_map.length; i = i + 3) | |
if (StaticUtil.url_param_map[i].equals(url)) { | |
String[] requestChecks = StaticUtil.url_param_map[i + 1].split(","); | |
trimAndSortStringArray(requestChecks); | |
Object[] requestKeys = requestParams.keySet().toArray(); | |
Arrays.sort(requestKeys); | |
if (!Arrays.equals(requestChecks, requestKeys)) { | |
IError e = new IError(); | |
e.errorMsg = "HTTP REQUEST ERROR==>" + url + " requestKeys: " + Arrays.toString(requestKeys) + " need 2 check " + Arrays.toString(requestChecks); | |
return e; | |
} | |
if(MyLog.DEBUG){ | |
for(String key : requestChecks){ | |
if(requestParams.get(key) == null){ | |
IError e = new IError(); | |
e.errorMsg = "HTTP REQUEST ERROR==>" + url + " request: " + requestParams + " key == null " + key; | |
return e; | |
} | |
} | |
} | |
} | |
return null; | |
} | |
private static void trimAndSortStringArray(String[] strs){ | |
for(int j = 0; j<strs.length; j++){ | |
strs[j] = strs[j].trim(); | |
} | |
Arrays.sort(strs); | |
} | |
public static IError responseParamCheck(String url, final Map<String, String> rawParams, JSONObject resultJson) { | |
//判断返回的参数是否正确,如果正确,返回null | |
for (int i = 0; i < StaticUtil.url_param_map.length; i = i + 3) { | |
if (StaticUtil.url_param_map[i].equals(url)) { | |
String[] requestChecks = StaticUtil.url_param_map[i + 2].split(","); | |
trimAndSortStringArray(requestChecks); | |
IError jsonError = JsonUtils.isJsonValid(resultJson, requestChecks); | |
if (jsonError != null) { | |
jsonError.errorMsg = "HTTP RESPONSE ERROR==>" + url + " param=>" + rawParams + " " + resultJson + " has no " + jsonError.errorMsg; | |
return jsonError; | |
} | |
break; | |
} | |
} | |
return null; | |
} | |
public static byte[] doHttpGet(String url) { | |
HttpClient httpClient = new DefaultHttpClient(); | |
if(url == null){ | |
throw new RuntimeException("url == null"); | |
} | |
try { | |
HttpGet getRequest = new HttpGet(url); | |
HttpResponse httpResponse = httpClient.execute(getRequest); | |
return EntityUtils.toByteArray(httpResponse.getEntity()); | |
} catch (Exception e) { | |
} | |
return null; | |
} | |
public static class HttpUtilJsonResponse { | |
public String url = null; | |
public JSONObject jo = null; | |
public IError e = null; | |
public String ret = null; | |
private StringBuffer requestAndResponseBuffer; | |
public HttpUtilJsonResponse() { | |
requestAndResponseBuffer = new StringBuffer(); | |
} | |
public boolean isError() { | |
return e != null; | |
} | |
public boolean checkRetSuccess() { | |
if (!isError() && !jo.isNull("ret")) { | |
try { | |
return jo.getString("ret").equals("0"); | |
} catch (JSONException e1) { | |
} | |
} | |
return false; | |
} | |
public String getSuccessDialogMsg() { | |
if (!isError() && checkRetSuccess()) { | |
return QrtUtils.getSuccessMsg(url); | |
} | |
return "无法获取成功信息==" + this.jo.toString(); | |
} | |
public String getErrorDialogMsg(String errorCode) { | |
if (!isError() && !checkRetSuccess()) { | |
return QrtUtils.getErrorMsg(errorCode).get("message"); | |
} | |
return "无法获取错误信息==" + this.jo.toString(); | |
} | |
public String getDialogMsg() { | |
String dialogMsg = null; | |
if (checkRetSuccess()) { | |
dialogMsg = getSuccessDialogMsg(); | |
} else { | |
dialogMsg = getErrorDialogMsg(getRet()); | |
} | |
return dialogMsg; | |
} | |
public String getRet() { | |
if (!isError() && !jo.isNull("ret")) { | |
try { | |
return jo.getString("ret"); | |
} catch (JSONException e1) { | |
} | |
} | |
return null; | |
} | |
public String getRequestAndResponse(){ | |
return requestAndResponseBuffer.toString(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.app.Activity; | |
import android.content.Context; | |
import android.content.DialogInterface; | |
import com.stonete.qrtoken.activity.IActivity; | |
import com.stonete.qrtoken.dialog.My_Dialog; | |
/** | |
* Created by kangwei on 2015/2/15. | |
*/ | |
public class IError { | |
public String errorMsg = null; | |
public int errorCode = -1; | |
public static final int ERROR_HTTP_500 = 500; | |
public void showErrorDialog(final Context context) { | |
String showMsg = errorMsg; | |
if(ifNeed2sendQQ()){ | |
showMsg = "当前为测试模式。Http请求发生错误,请您将错误日志发送给开发人员"; | |
} | |
MyLog.e(errorMsg); | |
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
if(ifNeed2sendQQ() && context instanceof Activity){ | |
AppUtils.sendLog2QQ((Activity) context, errorMsg); | |
} | |
} | |
}; | |
DialogUtils.showDialog(context, showMsg, listener); | |
} | |
public void printTestLog() { | |
MyLog.e(errorMsg); | |
} | |
public boolean ifNeed2sendQQ(){ | |
return MyLog.DEBUG && errorCode == 500; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import org.json.JSONObject; | |
/** | |
* Created by kangwei on 2015/2/15. | |
*/ | |
public class JsonUtils { | |
public static IError isJsonValid(JSONObject jo, String... pars) { | |
for (String par : pars) { | |
par = par.trim(); | |
if (jo.isNull(par)) { | |
IError error = new IError(); | |
error.errorMsg = jo + " has no param " + par; | |
return error; | |
} | |
} | |
return null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import java.io.UnsupportedEncodingException; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import android.content.Context; | |
import android.text.TextUtils; | |
import android.widget.Toast; | |
import com.stonete.qrtoken.dialog.GetToast; | |
public class JudgeUsername { | |
public static boolean getjudgeusername(Context context, String username) { | |
if (!judgeUsernameValid(username)) { | |
GetToast.showToast("用户名格式不正确", context); | |
return false; | |
} | |
return true; | |
} | |
public static boolean getValidPhoneNum(Context context, String phone){ | |
if(!RegexChecks.checkPhoneNum(phone)){ | |
Toast.makeText(context, "请正确填写11位手机号", Toast.LENGTH_SHORT).show(); | |
return false; | |
} | |
return true; | |
} | |
public static boolean judgeUsernameValid(String username) { | |
return RegexChecks.checkUserNameRegex(username); | |
} | |
//正则表达式 | |
public static boolean editText(String username) { | |
// ^(?!_)[a-zA-Z0-9_]*$ | |
// "([a-z]|[A-Z]|[0-9_]|[\\u4e00-\\u9fa5])+" | |
Pattern p = Pattern.compile("^(?!_)[a-zA-Z0-9_]*$"); | |
Matcher m = p.matcher(username); | |
if (m.matches()) { | |
return true; | |
} | |
return false; | |
} | |
public static boolean getValidSmsCode(Context context, String smsCode) { | |
if(TextUtils.isEmpty(smsCode)){ | |
Toast.makeText(context, "验证码错误", Toast.LENGTH_SHORT).show(); | |
return false; | |
} | |
return true; | |
} | |
public static boolean judgeEmail(Context context, String email) { | |
if(!RegexChecks.checkEmailRegex(email)){ | |
Toast.makeText(context, "邮箱格式不正确", Toast.LENGTH_SHORT).show(); | |
return false; | |
} | |
return true; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.content.Context; | |
import com.stonete.qrtoken.activity.IActivity; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.util.Calendar; | |
import java.util.UUID; | |
public class MyLog { | |
public static boolean DEBUG = true; | |
// --Commented out by Inspection (2015/3/4 11:58):private static Boolean MYLOG_WRITE_TO_FILE = false; | |
// --Commented out by Inspection (2015/3/4 11:58):private static SimpleDateFormat LOG_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |
private static String TAG = "MyLog"; | |
public static void w(String tag, String msg) { | |
if (!DEBUG) return; | |
msg = "==> " + msg; | |
android.util.Log.w(tag, msg); | |
} | |
public static void e(String tag, String xmsg) { | |
if (!DEBUG) return; | |
String msg = "==> " + xmsg; | |
android.util.Log.e(TAG, msg); | |
writeMsg2LogFile("E", xmsg); | |
} | |
public static void writeMsg2LogFile(String LogType,String msg){ | |
logFile = getLogFile(); | |
if(logFile!= null && logFile.canWrite()){ | |
try { | |
FileWriter writer = new FileWriter(logFile.getAbsolutePath(), true); | |
msg = TimeUtils.currentFormateData() + "= " + LogType + " =>" + msg + "\n"; | |
writer.write(msg); | |
writer.close(); | |
// android.util.Log.e(TAG, "LOG PATH=" + logFile.getAbsolutePath()); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static void e(String msg) { | |
e(TAG, msg); | |
} | |
public static void i(Object msg) { | |
i("MyLog", String.valueOf(msg)); | |
} | |
public static void d(String tag, String msg) { | |
if (!DEBUG) return; | |
android.util.Log.d(TAG, tag + msg); | |
} | |
public static void i(String tag, String msg) { | |
if (!DEBUG) return; | |
writeMsg2LogFile("I", tag + msg); | |
msg = "==> " + msg; | |
android.util.Log.i(TAG, tag + msg); | |
} | |
public static void v(String tag, String msg) { | |
msg = "==> " + msg; | |
if (!DEBUG) return; | |
android.util.Log.v(TAG, tag + msg); | |
} | |
private static boolean initLogFile() { | |
logFile = getLogFile(false); | |
return logFile != null; | |
} | |
public static File getLogFile(boolean random,int... errorCode){ | |
if (!DEBUG) return null; | |
Context ctx = IActivity.currentActivity; | |
String sdCardPath = null; | |
if(ctx != null){ | |
sdCardPath = FileUtils.getCatchPath(ctx); | |
} | |
if(sdCardPath == null){ | |
return null; | |
} | |
Calendar c = Calendar.getInstance(); | |
int month = c.get(Calendar.MONTH) + 1;// 获取当前月份 | |
int day = c.get(Calendar.DAY_OF_MONTH);// 获取当日期 | |
String xDay = month + "-" + day; | |
for(int ec : errorCode){ | |
xDay = xDay + "_" + ec; | |
} | |
String filedir = sdCardPath + "/" + xDay + ".txt"; | |
if(random){ | |
xDay = xDay + "_" + UUID.randomUUID().hashCode(); | |
filedir = sdCardPath + "/" + xDay + "response.htm"; | |
} | |
File file = new File(filedir); | |
if (!file.exists()) { | |
try { | |
file.createNewFile(); | |
MyLog.i("create log file " + filedir); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return file; | |
} | |
private static File logFile = null; | |
public static File getLogFile(){ | |
if(logFile == null){ | |
initLogFile(); | |
} | |
return logFile; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.content.Context; | |
import android.widget.Toast; | |
/** | |
* Created by kangwei on 2015/1/26. | |
*/ | |
public class MyToast { | |
public static void show(Context ctx, String msg) { | |
if (MyLog.DEBUG) { | |
Toast.makeText(ctx,ctx.getPackageName() + " Toast==>"+msg,Toast.LENGTH_SHORT).show(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import java.util.Hashtable; | |
import android.graphics.Bitmap; | |
import android.graphics.BitmapFactory; | |
import android.text.TextUtils; | |
import com.google.zxing.BinaryBitmap; | |
import com.google.zxing.ChecksumException; | |
import com.google.zxing.DecodeHintType; | |
import com.google.zxing.FormatException; | |
import com.google.zxing.NotFoundException; | |
import com.google.zxing.common.HybridBinarizer; | |
import com.google.zxing.qrcode.QRCodeReader; | |
import com.stonete.qrtoken.decoding.RGBLuminanceSource; | |
/** | |
* Created by kangwei on 2015/3/4. | |
*/ | |
public class QrCodeUtil { | |
public static String getQrCodeFromPhoto(String photoPath){ | |
if (TextUtils.isEmpty(photoPath)) { | |
return null; | |
} | |
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>(); | |
hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); | |
BitmapFactory.Options options = new BitmapFactory.Options(); | |
int sampleSize = (int) (options.outHeight / (float) 300); | |
if (sampleSize <= 0) sampleSize = 1; | |
options.inSampleSize = sampleSize; | |
Bitmap scanBitmap = BitmapFactory.decodeFile(photoPath, options); | |
RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap); | |
BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); | |
QRCodeReader reader = new QRCodeReader(); | |
String qrCode = null; | |
try { | |
qrCode = reader.decode(bitmap1, hints).getText(); | |
} catch (NotFoundException e) { | |
e.printStackTrace(); | |
} catch (ChecksumException e) { | |
e.printStackTrace(); | |
} catch (FormatException e) { | |
e.printStackTrace(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return qrCode; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.content.Context; | |
import android.util.ArrayMap; | |
import com.stonete.qrtoken.Bean.QrtUserInfo; | |
import com.stonete.qrtoken.sharedperfences.GetEmail; | |
import com.stonete.qrtoken.sharedperfences.GetTimeStamp; | |
import com.stonete.qrtoken.sharedperfences.GetUsername; | |
import com.stonete.qrtoken.sharedperfences.SharePrefUtil; | |
import com.stonete.qrtoken.statics.StaticUtil; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* 二维令的工具类 | |
* Created by kangwei on 2015/1/30. | |
*/ | |
public class QrtUtils { | |
public static boolean isNeed2TimeCheck(Context context) { | |
if (GetTimeStamp.getKey(context) == 0) { | |
GetTimeStamp.setKey(context, System.currentTimeMillis() / 1000); | |
return false; | |
} | |
//检查是否需要时间校验,如果5天还没有校验过,则校验 === 432000 | |
long result = Math.abs(System.currentTimeMillis() / 1000 - GetTimeStamp.getKey(context)); | |
MyLog.i("QRToken", "比较一下-" + System.currentTimeMillis() / 1000 + "-" + GetTimeStamp.getKey(context) + "=" + result + "=" + result / (60 * 60 * 24) + "天" + result % (60 * 60 * 24)); | |
return result > 432000; | |
} | |
public static Map<String,String> getErrorMsg(String errorCode){ | |
Map<String,String> map = new HashMap<String,String>(); | |
String[] errorMap = StaticUtil.errorMap; | |
for (int i = 0; i < errorMap.length; i = i + 3) { | |
if (errorMap[i].equals(errorCode.trim())) { | |
map.put("message", errorMap[i + 1]); | |
map.put("toastordialog", errorMap[i + 2]); | |
return map; | |
} | |
} | |
return map; | |
}; | |
public static void getDiaOrToast(Context context,String errorCode){ | |
Map<String, String> errorMsg1 = getErrorMsg(errorCode); | |
String message = errorMsg1.get("message"); | |
String toastordialog = errorMsg1.get("toastordialog"); | |
MyLog.i("message====>>"+message+"===toastordialog===>>"+toastordialog); | |
if (toastordialog.equals(StaticUtil.SHOW_TYPE_DIALOG)) | |
{ | |
DialogUtils.showDialog(context,message); | |
} else { | |
DialogUtils.showToast(context,message); | |
} | |
} | |
public static String getSuccessMsg(String url) { | |
String[] successMap = StaticUtil.successMap; | |
for (int i = 0; i < successMap.length; i = i + 2) { | |
if (successMap[i].equals(url.trim())) { | |
return successMap[i + 1]; | |
} | |
} | |
return "成功!"; | |
} | |
public static QrtUserInfo getCurrentUser(Context ctx) { | |
QrtUserInfo userInfo = new QrtUserInfo(); | |
userInfo.qrtUserName = SharePrefUtil.getUserName(ctx); | |
userInfo.email = GetEmail.getKey(ctx); | |
userInfo.hasBound = SharePrefUtil.ifHasBoundQrt(ctx); | |
return userInfo; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import com.stonete.qrtoken.application.SysApplication; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* Created by kangwei on 2015/3/5. | |
*/ | |
public class RegexChecks { | |
public static boolean checkEmailRegex(String email){ | |
Pattern pattern = Pattern.compile("^([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})(\\]?)$"); | |
Matcher matcher = pattern.matcher(email); | |
return matcher.matches(); | |
} | |
public static boolean checkUserNameRegex(String userName){ | |
String reg = "^[a-zA-Z]{1}\\w{4,19}$"; | |
return check(reg, userName); | |
} | |
public static boolean checkPhoneNum(String phone) { | |
String checkReg = "^1\\d{10}"; | |
return check(checkReg, phone); | |
} | |
public static boolean isAuthCode(String code){ | |
String checkReg = "^\\d{6}$"; | |
return check(checkReg, code); | |
} | |
public static boolean check(String checkReg, String str){ | |
Pattern pattern = Pattern.compile(checkReg); | |
Matcher matcher = pattern.matcher(str); | |
return matcher.matches(); | |
} | |
public static void main(String args[]) throws IOException { | |
String reg = ""; | |
String str = ""; | |
while (true) { | |
String input = getInput(); | |
if(input.startsWith("reg")){ | |
reg = input.substring("reg".length()); | |
System.out.println("输入了正则表达式" + reg); | |
} | |
else if(input.startsWith("str")){ | |
str = input.substring("str".length()); | |
System.out.println("输入了字符个数" + str.length()); | |
} | |
else if(input.equals("r")){ | |
System.out.println("reg:" + reg + "\nstr" + str); | |
try{ | |
System.out.println(check(reg, str)); | |
}catch (Exception e){ | |
e.printStackTrace(); | |
} | |
}else{ | |
System.out.println("无效的命令"); | |
} | |
} | |
} | |
public static String getInput() throws IOException { | |
System.out.println("请输入:"); | |
//^[a-zA-Z]{1}\w{4,19}$ | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
return br.readLine(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import java.math.BigInteger; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import android.content.Context; | |
import com.stonete.qrtoken.sharedperfences.GetEncryptLaterPrivate_Key; | |
public class SHA256Encrypt { | |
private static byte[] getHash(String password) { | |
MessageDigest digest = null; | |
try { | |
digest = MessageDigest.getInstance("SHA-256"); | |
} catch (NoSuchAlgorithmException e1) { | |
e1.printStackTrace(); | |
} | |
digest.reset(); | |
return digest.digest(password.getBytes()); | |
} | |
public static String bin2hex(String strForEncrypt) { | |
byte[] data = getHash(strForEncrypt); | |
return String.format("%0" + (data.length * 2) + "X", new BigInteger(1, data)); | |
} | |
public static String getsharedperMD5(Context ctx) { | |
String mprikey = GetEncryptLaterPrivate_Key.getprivatekey(ctx); | |
// 对私钥进行sha256加密 | |
try { | |
String msha256 = SHA256Encrypt.bin2hex(mprikey); | |
String nsha256 = msha256.toLowerCase(); | |
return nsha256; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.content.ContentResolver; | |
import android.content.Context; | |
import android.database.Cursor; | |
import android.net.Uri; | |
/** | |
* Created by kangwei on 15/4/10. | |
*/ | |
public class SmsUtil { | |
public static String getSms(Context ctx){ | |
ContentResolver contentResolver = ctx.getContentResolver(); | |
Uri uri = Uri.parse("content://sms"); | |
Long now = System.currentTimeMillis(); | |
String selection = "date>" + now; | |
Cursor cursor = contentResolver.query(uri, null, selection, null, null); | |
int second = 0; | |
while(second<60 && !cursor.moveToFirst()){ | |
cursor.close(); | |
cursor = contentResolver.query(uri, null, selection, null, null); | |
second++; | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}; | |
if(second != 60){ | |
String phone = cursor.getString(cursor.getColumnIndex("address")); | |
int type = cursor.getInt(cursor.getColumnIndex("type"));// 2 = sent, etc. | |
String date = cursor.getString(cursor.getColumnIndex("date")); | |
String body = cursor.getString(cursor.getColumnIndex("body")); | |
cursor.close(); | |
MyLog.i(phone + " " + type + " " + date + " " + body); | |
if(body.contains("验证码是:")){ | |
String yzm = body.split("验证码是:")[1].substring(0,6); | |
return yzm; | |
} | |
return null; | |
} | |
cursor.close(); | |
return null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import java.io.IOException; | |
import android.app.Activity; | |
import android.content.Context; | |
import android.content.res.AssetFileDescriptor; | |
import android.media.AudioManager; | |
import android.media.MediaPlayer; | |
import android.os.Vibrator; | |
import com.stonete.qrtoken.R; | |
/** | |
* Created by kangwei on 2015/3/4. | |
*/ | |
public class SoundUtil { | |
private static final float BEEP_VOLUME = 0.10f; | |
private static final long VIBRATE_DURATION = 200L; | |
private static final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() { | |
public void onCompletion(MediaPlayer mediaPlayer) { | |
mediaPlayer.seekTo(0); | |
} | |
}; | |
public static void beep(Activity act){ | |
act.setVolumeControlStream(AudioManager.STREAM_MUSIC); | |
MediaPlayer mediaPlayer = new MediaPlayer(); | |
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); | |
mediaPlayer.setOnCompletionListener(beepListener); | |
AssetFileDescriptor file = act.getResources().openRawResourceFd(R.raw.beep); | |
try { | |
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); | |
file.close(); | |
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); | |
mediaPlayer.prepare(); | |
mediaPlayer.start(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
Vibrator vibrator = (Vibrator) act.getSystemService(Context.VIBRATOR_SERVICE); | |
vibrator.vibrate(VIBRATE_DURATION); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
/** | |
* Created by lxzMac on 15/3/27. | |
*/ | |
public class TestUtil { | |
public static String formatAddLine(String str, int joinLin){ | |
return null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.app.Activity; | |
import android.content.Context; | |
import android.graphics.Canvas; | |
import android.graphics.Color; | |
import android.graphics.Paint; | |
import android.util.AttributeSet; | |
import android.widget.TextView; | |
public class TextViewUtil extends TextView { | |
/** | |
* 字体大小 | |
*/ | |
private static final int TEXT_SIZE = 18; | |
// --Commented out by Inspection START (2015/3/4 11:58): | |
// /** | |
// * 距离右面的大小 | |
// */ | |
// private static final int TEXT_right = 15; | |
// --Commented out by Inspection STOP (2015/3/4 11:58) | |
// --Commented out by Inspection START (2015/3/4 11:58): | |
// /** | |
// * textview 的行间距 | |
// */ | |
// private static final int LINE_SPAC = 15; | |
// --Commented out by Inspection STOP (2015/3/4 11:58) | |
/** | |
* 手机的屏幕密度 | |
*/ | |
private static float density; | |
private final String namespace = "http://www.angellecho.com/"; | |
private String text; | |
private float textSize; | |
private float paddingLeft; | |
private float paddingRight; | |
private float marginLeft; | |
private float marginRight; | |
// --Commented out by Inspection (2015/3/4 11:58):private float linespac; | |
private int textColor; | |
private Paint paint1 = new Paint(); | |
private float textShowWidth; | |
// --Commented out by Inspection START (2015/3/4 11:58): | |
// /** | |
// * | |
// */ | |
// private int ScreenRate; | |
// --Commented out by Inspection STOP (2015/3/4 11:58) | |
public TextViewUtil(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
density = context.getResources().getDisplayMetrics().density; | |
// 将像素转换成dp | |
text = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "text"); | |
textSize = attrs.getAttributeIntValue(namespace, "textSize", TEXT_SIZE); | |
textColor = attrs.getAttributeIntValue(namespace, "textColor", Color.GRAY); | |
paddingLeft = attrs.getAttributeIntValue(namespace, "paddingLeft", 0) * density; | |
paddingRight = attrs.getAttributeIntValue(namespace, "paddingRight", 80) * density; | |
marginLeft = attrs.getAttributeIntValue(namespace, "marginLeft", 0) * density; | |
marginRight = attrs.getAttributeIntValue(namespace, "marginRight", 0) * density; | |
paint1.setTextSize(textSize * density); | |
paint1.setColor(textColor); | |
paint1.setAntiAlias(true); | |
textShowWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth() - paddingLeft - paddingRight - marginLeft - marginRight; | |
} | |
@Override | |
protected void onDraw(Canvas canvas) { | |
int lineCount = 0; | |
text = this.getText().toString();//.replaceAll("\n", "\r\n"); | |
if (text == null) return; | |
char[] textCharArray = text.toCharArray(); | |
// 已绘的宽度 | |
float drawedWidth = 0; | |
float charWidth; | |
for (int i = 0; i < textCharArray.length; i++) { | |
charWidth = paint1.measureText(textCharArray, i, 1); | |
if (textCharArray[i] == '\n') { | |
lineCount++; | |
drawedWidth = 0; | |
continue; | |
} | |
if (textShowWidth - drawedWidth < charWidth) { | |
lineCount++; | |
drawedWidth = 0; | |
} | |
canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth, | |
(lineCount + 1) * textSize * density, paint1); | |
drawedWidth += charWidth; | |
} | |
setHeight((lineCount + 1) * (int) (textSize * density) + 5); | |
// FontMetrics fm = paint1.getFontMetrics(); | |
// float baseline = fm.descent - fm.ascent; | |
// float x = 0; | |
// float y = baseline; //由于系统基于字体的底部来绘制文本,所有需要加上字体的高度。 | |
// canvas.drawText(text, x, y, paint1); //坐标以控件左上角为原点 | |
// y += baseline + fm.leading; //添加字体行间距 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import java.text.SimpleDateFormat; | |
import java.util.Date; | |
/** | |
* Created by kangwei on 2015/3/19. | |
*/ | |
public class TimeUtils { | |
public static void main(String[] args){ | |
System.out.println(1); | |
new Date(); | |
} | |
public static String currentFormateData(){ | |
return dateToString(new Date()); | |
} | |
public static String dateToString(Date time){ | |
SimpleDateFormat formatter; | |
formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); | |
String ctime = formatter.format(time); | |
return ctime; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import android.content.Context; | |
import com.umeng.analytics.MobclickAgent; | |
import com.umeng.update.UmengDialogButtonListener; | |
import com.umeng.update.UmengUpdateAgent; | |
import com.umeng.update.UmengUpdateListener; | |
import com.umeng.update.UpdateResponse; | |
import com.umeng.update.UpdateStatus; | |
/** | |
* 友盟更新+是否需要强制更新 | |
* | |
* @author luwenzheng | |
*/ | |
public class UmengUpdateUtil { | |
public static void prepare4UmengUpdate(final Context context) { | |
MobclickAgent.updateOnlineConfig(context); | |
//获取友盟在线参数 | |
String update_mode = MobclickAgent.getConfigParams(context, "upgrade_mode"); | |
if (update_mode == null || "".equals(update_mode)) { | |
return; | |
} | |
String mUpdateModeArray[]; | |
//转换为数组 | |
mUpdateModeArray = update_mode.split(","); | |
UmengUpdateAgent.setUpdateOnlyWifi(false); //在任意网络环境下都进行更新自动提醒 | |
final UpdateResponse[] mUpdateResponse = new UpdateResponse[1]; | |
UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() { | |
public void onUpdateReturned(int i, UpdateResponse updateResponse) { | |
mUpdateResponse[0] = updateResponse; | |
} | |
}); | |
UmengUpdateAgent.forceUpdate(context); //调用umeng更新接口 | |
String curr_version_name = AppUtils.getVersionNameByPkgName(context, context.getPackageName()); | |
for (int i = 0; i < mUpdateModeArray.length; i += 2) { | |
if (curr_version_name.equals(mUpdateModeArray[i])) { | |
if ("F".equals(mUpdateModeArray[i + 1])) { | |
//对话框按键的监听,对于强制更新的版本,如果用户未选择更新的行为,关闭app | |
UmengUpdateAgent.setDialogListener(new UmengDialogButtonListener() { | |
@Override | |
public void onClick(int status) { | |
switch (status) { | |
case UpdateStatus.Update: | |
break; | |
default: | |
//"以后再说" 进行重复显示此显示升级Dialog | |
UmengUpdateAgent.showUpdateDialog(context, mUpdateResponse[0]); | |
} | |
} | |
}); | |
break; //只要找到对应的版本号,即结束循环 | |
} | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.stonete.qrtoken.utils; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.StringBufferInputStream; | |
import java.io.StringWriter; | |
import java.util.HashMap; | |
import java.util.Iterator; | |
import java.util.Map; | |
import java.util.Set; | |
import org.xmlpull.v1.XmlPullParser; | |
import org.xmlpull.v1.XmlPullParserException; | |
import org.xmlpull.v1.XmlSerializer; | |
import android.util.Xml; | |
public class XmlUtils { | |
/** | |
* 生成xml | |
* createXml(HashMap<String,String>, map) returnType xmlString | |
*/ | |
public static String createXml(HashMap<String, String> map) { | |
XmlSerializer serializer = Xml.newSerializer(); | |
StringWriter writer = new StringWriter(); | |
try { | |
serializer.setOutput(writer); | |
serializer.startDocument("gbk", null); | |
// <result> | |
serializer.startTag("", "result");// 第一个参数是命名空间,第二个是标签名 | |
// <status>0</status><#!– 返回状态 0成功, 2000失败 ,1001未绑定–> | |
Set set = map.entrySet(); | |
Iterator it = set.iterator(); | |
while (it.hasNext()) { | |
Map.Entry entry = (Map.Entry) it.next(); | |
serializer.startTag("", (String) entry.getKey()); | |
serializer.text((String) entry.getValue()); | |
serializer.endTag("", (String) entry.getKey()); | |
} | |
// </result> | |
serializer.endTag("", "result"); | |
serializer.endDocument(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return writer.toString(); | |
} | |
/** | |
* 解析xml | |
* parseXml(String xml) resturnType HashMap<String,String> | |
*/ | |
public static HashMap<String, String> parseXml(String xml) { | |
HashMap<String, String> map = null; | |
try { | |
InputStream sis = new StringBufferInputStream(xml); | |
XmlPullParser parser = Xml.newPullParser(); | |
parser.setInput(sis, "gbk"); | |
// 开始解析事件 | |
int eventType = parser.getEventType(); | |
// 处理事件,不碰到文档结束就一直处理 | |
while (eventType != XmlPullParser.END_DOCUMENT) { | |
// 因为定义了一堆静态常量,所以这里可以用switch | |
switch (eventType) { | |
case XmlPullParser.START_DOCUMENT: | |
// 不做任何操作或初开始化数据 | |
map = new HashMap<String, String>(); | |
break; | |
case XmlPullParser.START_TAG: | |
String tagName = parser.getName(); | |
if (!"result".equals(tagName)) { | |
// 属性值为: | |
// String statue_id = parser.getAttributeName(0); | |
// map.put(statue_id, statue_id); | |
// 节点值为: | |
parser.next(); | |
String value = parser.getText(); | |
map.put(tagName, value); | |
} | |
break; | |
case XmlPullParser.END_TAG: | |
break; | |
case XmlPullParser.END_DOCUMENT: | |
break; | |
} | |
eventType = parser.next(); | |
} | |
} catch (XmlPullParserException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return map; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment