/**
* 直接下載圖片並加載至控件(非異步加載)
*
* @param activity
* @param urlpath
* 圖片下載路徑
* @param imageView
* 目標控件
* @param isStretch
* 是否拉伸圖片
* @param screenWidth
* 屏幕寬度
* @return
*/
public static String loadImageFromNetURL(Activity activity, String urlpath,
ImageView imageView, Boolean isStretch, int screenWidth) {
String strpic;
try {
strpic = Methods.downloadFile(activity, urlpath);
if (null == strpic) {
Log.i("ResultBaseActivity", "圖片下載失敗!");
}
if (isStretch) {
imgStretchMatchScreen(imageView,
BitmapFactory.decodeFile(strpic), screenWidth);
} else {
imageView.setImageURI(Uri.parse(strpic));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return strpic;
}
/**
* 加載本地圖片至控件
*
* @param activity
* @param urlpath
* 圖片路徑
* @param imageView
* 目標控件
* @param isStretch
* 是否拉伸
* @param screenWidth
* 屏幕寬度
* @return
*/
public static String loadImageFromLocalURL(Activity activity,
String urlpath, ImageView imageView, Boolean isStretch,
int screenWidth) {
try {
if (isStretch) {
imgStretchMatchScreen(imageView,
BitmapFactory.decodeFile(urlpath), screenWidth);
} else {
imageView.setImageURI(Uri.parse(urlpath));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return urlpath;
}
/**
* 根據下載網址,判斷該圖片是否已下載,如已下載則返回圖片路徑,不然返回null
*
* @param activity
* @param urlpath
* @return
*/
public static String downloadImageCheck(Activity activity, String urlpath) {
String newFile;
String IMGType = urlpath.substring(urlpath.lastIndexOf("/") + 1);
if (Methods.chkSDCardState() || IMGType.length() >= 4) {
newFile = Environment.getExternalStorageDirectory() + "/bobing/"
+ IMGType;
} else {
newFile = activity.getCacheDir() + "/" + IMGType;
}
File file = new File(newFile);
if (!file.exists()) {
return null;
}
return newFile;
}
/**
* 下載文件,並返回保存路徑
*
* @param activity
* @param urlpath
* @return
* @throws Exception
*/
public static String downloadFile(Activity activity, String urlpath)
throws Exception {
String newFile;
String IMGType = urlpath.substring(urlpath.lastIndexOf("/") + 1);
if (Methods.chkSDCardState() || IMGType.length() >= 4) {
newFile = Environment.getExternalStorageDirectory() + "/bobing/"
+ IMGType;
Log.i("下載SDcard路徑", newFile);
} else {
newFile = activity.getCacheDir() + "/" + IMGType;
Log.i("下載內存路徑", newFile);
}
File file = new File(newFile);
File fileDirectory = file.getParentFile();// 獲取文件目錄
if (!fileDirectory.exists()) {
fileDirectory.mkdirs();
}
if (file.exists()) {
Log.i("該圖片已下載過", newFile);
return newFile;
}
String ret = null;
// 創建URL對象,拋出異常
java.net.URL url = new java.net.URL(urlpath);
// 獲得HttpURLConnection對象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 聲明請求方式
conn.setRequestMethod("GET");
// 設置鏈接超時
conn.setConnectTimeout(6 * 1000);
// 鏈接成功
if (conn.getResponseCode() == 200) {
// 獲得服務器傳回來的數據,相對咱們來講輸入流
InputStream inputStream = conn.getInputStream();
// 聲明緩衝區
byte[] buffer = new byte[1024];
// 定義讀取默認長度
int length = -1;
// 建立保存文件
// 建立一個文件輸出流
FileOutputStream outputStream = new FileOutputStream(newFile);
// 將咱們所得的二進制數據所有寫入咱們建好的文件中
while ((length = inputStream.read(buffer)) != -1) {
// 把緩衝區中輸出到內存中
outputStream.write(buffer, 0, length);
}
ret = newFile;
// 關閉輸出流
outputStream.close();
// 關閉輸入流
inputStream.close();
}
return ret;
}
static void imgStretchMatchScreen(ImageView iView, Bitmap bitmap,
int screenWidth) {
int margin = 10; // 左右兩邊到壁的距離
if (screenWidth >= 600) // PublicData.screenWidth是手機屏幕的寬度
{
margin = 30;
} else if (screenWidth >= 480) {
margin = 20;
} else if (screenWidth >= 320) {
margin = 15;
} else {
margin = 12;
}
int drawableWidth = screenWidth - margin; // margin是左右兩邊到壁的距離
int drawableHeight = drawableWidth * bitmap.getHeight()
/ bitmap.getWidth();
LayoutParams params = new LayoutParams(drawableWidth, drawableHeight);
params.setMargins(2, 20, 0, 0);
iView.setLayoutParams(params);
iView.setBackgroundDrawable(bitmap2Drawable(bitmap));
}
/**
* 將Bitmap轉化爲drawable
*
* @param bitmap
* @return
*/
public static Drawable bitmap2Drawable(Bitmap bitmap) {
return new BitmapDrawable(bitmap);
}
/**
* 將Drawable 轉 bitmap
*
* @param drawable
* @return
*/
public static Bitmap drawable2Bitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof NinePatchDrawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
} else {
return null;
}
}
/**
* 檢查讀卡器狀態
*
* @return
*/
public static Boolean chkSDCardState() {
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
}
/**
* 讀取文件內容,默認使用UTF-8編碼方式讀取,返回字符串
*
* @param context
* @param path
* @param encoding
* @return
* @throws Exception
*/
public static String readFile(Context context, String path, String encoding)
throws Exception {
FileInputStream inStream = new FileInputStream(path);
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();// 獲得文件的二進制數據
outStream.close();
inStream.close();
if (null == encoding || encoding == "") {
encoding = "UTF-8";
}
return new String(data, encoding);
}
/**
* 獲取經緯度
*
* @param context
* @return
*/
public static Map<String, Double> getLocation(Context context) {
if (locationUtil == null) {
locationUtil = new LocationUtil(context);
}
return locationUtil.returnLocation();
}
/**
* 根據經緯度獲取地址
*
* @param context
* @param map
* @return
*/
public static String getAddress(Context context, Map<String, Double> map) {
if (locationUtil == null) {
locationUtil = new LocationUtil(context);
}
return locationUtil.getAddressbyGeoPoint(map);
}
// 定義緩衝大小
final static int BUFFER_SIZE = 4096;
/**
* 將輸入流轉化爲字符串,默認使用utf-8編碼
*
* @param in
* @param encoding
* @return
* @throws Exception
*/
public static String convert_InputStreamTOString(InputStream in,
String encoding) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
data = null;
return new String(outStream.toByteArray(), encoding == null ? "UTF-8"
: encoding);
}
/**
* 將String轉換爲輸入流
*
* @param in
* @return
* @throws Exception
*/
public static InputStream convert_StringTOInputStream(String in)
throws Exception {
if (in != null) {
ByteArrayInputStream is = new ByteArrayInputStream(
in.getBytes("UTF-8"));
return is;
} else {
return null;
}
}
/**
* 將InputStream轉換成byte數組
*
* @param in
* @return
* @throws IOException
*/
public static byte[] convert_InputStreamTOByte(InputStream in)
throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
data = null;
return outStream.toByteArray();
}
/**
* 將byte數組轉換成InputStream
*
* @param in
* @return
* @throws Exception
*/
public static InputStream convert_byteTOInputStream(byte[] in)
throws Exception {
ByteArrayInputStream is = new ByteArrayInputStream(in);
return is;
}
/**
* 將byte數組轉換成String
*
* @param in
* @return
* @throws Exception
*/
public static String convert_byteTOString(byte[] in) throws Exception {
InputStream is = convert_byteTOInputStream(in);
return convert_InputStreamTOString(is, null);
}
/**
* 從webservice獲取返回的XML
*
* @param url
* @param map
* @return
*/
public static String getXML(String url, Map<String, String> map) {
System.out.println("url:" + url);
String result = null;
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpResponse response;
if (map == null) {
HttpGet request = new HttpGet(url);
response = client.execute(request);
} else {
JSONObject json = new JSONObject();
Set<String> key = map.keySet();
for (Iterator<String> it = key.iterator(); it.hasNext();) {
String s = it.next();
json.put(s, map.get(s));
}
String jsonString = chinaToUnicode(json.toString());
Log.i("請求參數JSON", jsonString);
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(jsonString
.getBytes("UTF8")));
request.setHeader("json", jsonString);
response = client.execute(request);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
Log.i("Read from server", result);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 將InputStream轉爲String
*
* @param is
* @return
* @throws UnsupportedEncodingException
*/
public static String convertStreamToString(InputStream is)
throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String rtn = decodeUnicode(sb.toString());
return rtn;
}
/**
* 把中文轉成Unicode碼
*
* @param str
* @return
*/
public static String chinaToUnicode(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
int chr1 = str.charAt(i);
if (chr1 >= 19968 && chr1 <= 171941) {// 漢字範圍 \u4e00-\u9fa5 (中文)
result += "\\u" + Integer.toHexString(chr1);
} else {
result += str.charAt(i);
}
}
return result;
}
/**
* 判斷是否爲中文字符
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
/**
* 將Unicode機器碼轉爲String
*
* @param theString
* @return
*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
aChar = '\t';
} else if (aChar == 'r') {
aChar = '\r';
} else if (aChar == 'n') {
aChar = '\n';
} else if (aChar == 'f') {
aChar = '\f';
}
outBuffer.append(aChar);
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
/**
* 根據文件路徑將文件轉化爲String(Base64編碼)
*
* @param strFilePath
* @return
*/
public static String convertFileToString(String strFilePath) {
try {
FileInputStream fis = new FileInputStream(strFilePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) >= 0) {
baos.write(buffer, 0, count);
}
fis.close();
return new String(Base64.encodeBase64(baos.toByteArray())); // 進行Base64編碼
} catch (Exception e) {
return null;
}
}
/**
* 上傳圖片至服務器:先轉換爲Base64格式的二進制字符串
*
* @param netURL
* 網絡URL
* @param srcpath
* 文件所在目錄路徑
* @param fileName
* 文件名稱
* @param map
*/
public static String fileUpload(String netURL, Map<String, String> map) {
String string = Methods.getXML(netURL, map); // 調用webservice
Log.i("connectWebService", "圖片上傳完成返回值:" + string.length());
return string;
}
/**
* 將對象轉換爲輸出流並進行Base64編碼後返回字符串
*
* @param object
* @return
*/
public static String convertObjectToString(Object object) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(3000);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
} catch (IOException e) {
e.printStackTrace();
}
// 將Product對象轉換成byte數組,並將其進行base64編碼
return new String(Base64.encodeBase64(baos.toByteArray()));
}
/**
* 將字符串用base64解碼並轉化爲輸入流後經過readObject轉換爲Object
*
* @param str
* @return
*/
public static Object convertStringToObject(String str) {
// 對Base64格式的字符串進行解碼
byte[] base64Bytes = Base64.decodeBase64(str.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois;
try {
ois = new ObjectInputStream(bais);
// 從ObjectInputStream中讀取Product對象
return ois.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1))
+ 0;
listView.setLayoutParams(params);
}
public static void setListViewHeightBasedOnChildren1(Activity activity,
ListView listView, int addHight) {
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = activity.getWindowManager().getDefaultDisplay()
.getHeight()
+ addHight;
listView.setLayoutParams(params);
}
/**
* 調用系統瀏覽器打開網頁
*
* @param activity
* @param str
*/
public static void openWeb(Activity activity, String str) {
Uri uri = Uri.parse(str);
activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
/**
* 上傳文件
*
* @param strURL
* @param strPath
*/
public static void uploadFile(String strURL, String strPath) {
System.out.println("上傳路徑:" + strURL);
final File fileTemp = new File(strPath);
final String strUrl = strURL;
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(strUrl);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url
.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod("POST");
OutputStream os = httpUrlConnection.getOutputStream();
BufferedInputStream fis = new BufferedInputStream(
new FileInputStream(fileTemp));
int bufSize = 0;
byte[] buffer = new byte[1024];
while ((bufSize = fis.read(buffer)) != -1) {
os.write(buffer, 0, bufSize);
}
fis.close();
BufferedReader reader = new BufferedReader(
new InputStreamReader(httpUrlConnection
.getInputStream()));
while (reader.readLine() != null) {
String responMsg = reader.readLine();
System.out.println("respinMsg" + responMsg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
* 採用線程更新網絡狀態
*
* @param context
*/
public static void refreshAPNType(final Context context) {
new Thread(new Runnable() {
@Override
public void run() {
Methods.netWorkType = getAPNType(context);
}
}).start();
}
/**
* 獲取當前的網絡狀態 :沒有網絡0:WIFI網絡1:3G網絡2:2G網絡3
*
* @param context
* @return
*/
private static int getAPNType(Context context) {
int netType = 0;
ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo == null) {
return netType;
}
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_WIFI) {
netType = 1;// wifi
} else if (nType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager mTelephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
&& !mTelephony.isNetworkRoaming()) {
netType = 2;// 3G
} else {
netType = 3;// 2G
}
}
return netType;
}
public static void solveThreadProblem() {
// 解決線程異常問題android.os.NetworkOnMainThreadException
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
}
/**
* 自動判斷文件保存路徑
*
* @return
*/
public static String getAutoDirectory() {
if (Methods.chkSDCardState()) {
return Environment.getExternalStorageDirectory() + "/ppk365/";
} else {
return "/data/data/com.ppk365.bobing/cache/";
}
}
/**
* 重寫back按鍵
* */
public static void backdailog(Activity activity) {
final ModelDialog dialog = new ModelDialog(activity,
R.layout.dialog_back, R.style.Theme_dialog);
dialog.show();
ImageButton btnok = (ImageButton) dialog.findViewById(R.id.btn_ok_back);
btnok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
});
ImageButton btnCancel = (ImageButton) dialog
.findViewById(R.id.btn_cancel_back);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
public static void requestFocus1(View view) {
view.setFocusable(true);
view.requestFocus();
view.setFocusableInTouchMode(true);
}
/**
* 隱藏軟鍵盤
*
* @param view
*/
public static void hideSoftInput(Activity activity, View view) {
if (!(view instanceof EditText)) {
try {
((InputMethodManager) activity
.getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(activity.getCurrentFocus()
.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
}
}
}
/**
* QQ登陸成功返回
*/
public static void login_QQ_WEIBO(Activity activity, String strSid) {
/*
* SharePreferencesUser sp = new SharePreferencesUser(
* activity.getApplicationContext()); sp.setUserID(strSid);
* sp.saveUserInfo("", ""); Methods.mIsLogin = true; Methods.mUID =
* strSid; Intent mIntent = new Intent(activity,
* UserManagerActivity.class);
* mIntent.putExtra(CST_SharePreferName.USERMAIN_OBJ, R.id.doLoadNet);
* Methods.mainActivity.SwitchActivity(mIntent, "UserManagerActivity");
*/
}
/**
* MD5加密
*
* @param str
* @return
*/
private static String getMD5Str(String str) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(str.getBytes("UTF-8"));
} catch (Exception e) {
System.out.println("NoSuchAlgorithmException caught!");
}
byte[] byteArray = messageDigest.digest();
StringBuffer md5StrBuff = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
md5StrBuff.append("0").append(
Integer.toHexString(0xFF & byteArray[i]));
else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
}
// 16位加密,從第9位到25位
return md5StrBuff.substring(8, 24).toString().toUpperCase();
}
public static String CheckVersion(Context context) {
String strXML = getXML(ConstantURL.CHECK_VERSION_APK, null);
if (strXML != null) {
APKVersion apkVersion = (APKVersion) getParserFromXmlObject(strXML,
APKVersion.class);
try {
Methods.publishDate = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").parse(apkVersion.getDfabsj());
} catch (Exception e) {
e.printStackTrace();
}
if (apkVersion.getIsSuccess().equals("1")) {
String thisPublishStr = context.getResources().getString(
R.string.apk_version);
if (thisPublishStr.contains(".")) {
// 正式版
String strSVersion = null;
Float intSVersion = (float) 0;
try {
strSVersion = apkVersion.getNbanbh();
intSVersion = Float.parseFloat(strSVersion);
String strNowVersion = context.getResources()
.getString(R.string.apk_version);
String strVer = strNowVersion.substring(0,
strNowVersion.lastIndexOf("."))
+ strNowVersion
.charAt(strNowVersion.length() - 1);
// 將 1.2.3 轉換爲1.23
Float versionCode = Float.parseFloat(strVer);
if (versionCode < intSVersion) {
return apkVersion.getCurl();
}
} catch (Exception e) {
}
} else {
// 內測版
thisPublishStr = "20" + thisPublishStr.substring(0, 2)
+ "-" + thisPublishStr.substring(2, 4) + "-"
+ thisPublishStr.substring(4) + " 00:00:00";
try {
Date thisPublishDate = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").parse(thisPublishStr);
if (thisPublishDate.getTime() < Methods.publishDate
.getTime()) {
return apkVersion.getCurl();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
return "";
}
/**
* 開啓服務下載安裝包
*
* @param context
* @param httpUrl
* @param strUpdateInfo
* @param startActivity
* 是否建立下載界面
*/
public static void startAPKdownLoadService(final Context context,
final String httpUrl, String strUpdateInfo, boolean startActivity) {
System.out.println("啓動服務:UpgradeService");
Methods.openDownload = true;
// 啓動下載Service
Intent intent = new Intent();
intent.setClass(context, UpgradeService.class);
Methods.httpUrl = httpUrl;
context.startService(intent);
if (startActivity) {
// 打開下載activity
Intent intent2 = new Intent();
intent2.setClass(context, UpdateAppActivity.class);
intent2.putExtra(ConstantURL.UPDATE_INFO, strUpdateInfo);
context.startActivity(intent2);
}
}
/**
* 終止安裝包下載服務
*
* @param context
* @param clazz
*/
public static void stopAPKdownLoadService(final Context context,
Class<?> clazz) {
if (isServiceRunning(context, clazz)) {
System.out.println("中止服務:" + clazz.getName());
Methods.openDownload = false;
Intent intent = new Intent();
intent.setClass(context, clazz);
context.stopService(intent);
}
}
/**
* 用來判斷服務是否運行.
*
* @param context
* @param className
* 判斷的服務名字
* @return true 在運行 false 不在運行
*/
public static boolean isServiceRunning(Context mContext, Class<?> clazz) {
boolean isRunning = false;
ActivityManager activityManager = (ActivityManager) mContext
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(30);
if (!(serviceList.size() > 0)) {
return false;
}
for (int i = 0; i < serviceList.size(); i++) {
if (serviceList.get(i).service.getClassName().equals(
clazz.getName()) == true) {
isRunning = true;
break;
}
}
return isRunning;
}
/**
* 顯示並賦值給標題左邊按鈕
*
* @param activity
* @param intString
* @return
*/
public static View findHeadLeftView(Activity activity, int intString) {
FrameLayout mLayout = (FrameLayout) activity
.findViewById(R.id.mhead_left_layout);
mLayout.setVisibility(View.VISIBLE);
if (intString != 0) {
TextView tView = (TextView) mLayout
.findViewById(R.id.mhead_left_layout_tv);
tView.setText(activity.getResources().getString(intString));
}
return activity.findViewById(R.id.mhead_left_img);
}
/**
* 顯示並賦值給標題右邊按鈕
*
* @param activity
* @param intString
* @return
*/
public static View findHeadRightView(Activity activity, int intString) {
FrameLayout mLayout = (FrameLayout) activity
.findViewById(R.id.mhead_right_layout);
mLayout.setVisibility(View.VISIBLE);
if (intString != 0) {
TextView tView = (TextView) mLayout
.findViewById(R.id.mhead_right_layout_tv);
tView.setText(activity.getResources().getString(intString));
}
return activity.findViewById(R.id.mhead_right_img);
}
/**
* 登陸
*
* @param username
* 用戶名
* @param password
* 密碼
* */
public static Login LoginToServer(Context context, String username,
String password) {
final HashMap<String, String> map = new HashMap<String, String>();
map.put("nmobile", username);
map.put("cpassword", password);
try {
String mXml = Methods.getXML(ConstantURL.LOGIN, map);
return (Login) XmlParse.getXmlObject(mXml, Login.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 給標題框添加標題
*
* @param activity
* @param stringTitle
* @return
*/
public static TextView findHeadTitle(Activity activity, int stringTitle) {
TextView textView = (TextView) activity
.findViewById(R.id.mhead_title_tv);
if (stringTitle != 0) {
textView.setText(activity.getResources().getString(stringTitle));
}
return textView;
}
/**
* 網絡鏈接超時提示
*
* @param context
*/
public static void ToastFailNet(Context context) {
Toast.makeText(context, "鏈接超時,請檢查網絡", 0).show();
}
/**
* 服務器出錯提示
*
* @param context
*/
public static void ToastFail(Context context) {
Toast.makeText(context, "服務出錯", 0).show();
}
/**
* 計算字符串中指定子字符串出現的次數
*
* @param strString
* @param suffix
* @return
*/
public static int getCountIndex(String strString, String suffix) {
if (strString == null || suffix == null) {
return 0;
} else if (strString.equals(suffix)) {
return 1;
}
if (strString.startsWith(suffix)) {
strString = strString.substring(1);
}
if (strString.endsWith(suffix)) {
strString = strString.substring(0, strString.length() - 2);
}
int rows = 1;
while (strString.contains(suffix)) {
rows++;
strString = strString.substring(strString.indexOf(suffix) + 1);
}
return rows;
}
/**
* 用指定字符做爲分隔符將字符串分解成數組
*
* @param strString
* @param suffix
* @return
*/
public static String[] StringToStringArray(String strString, String suffix) {
int rows = getCountIndex(strString, suffix);
if (strString.startsWith(suffix)) {
strString = strString.substring(1);
}
if (strString.endsWith(suffix)) {
strString = strString.substring(0, strString.length() - 1);
}
if (rows == 0) {
return null;
}
String[] strArray = new String[rows];
if (rows == 1) {
strArray[0] = strString;
} else {
String tmpString = strString;
for (int i = 0; i < strArray.length - 1; i++) {
strArray[i] = tmpString.substring(0, tmpString.indexOf(suffix));
if (i == strArray.length - 2) {
strArray[strArray.length - 1] = tmpString
.substring(tmpString.indexOf(suffix) + 1);
} else {
tmpString = tmpString
.substring(tmpString.indexOf(suffix) + 1);
}
}
}
return strArray;
}
/**
* 判斷字符串中是否存在指定的子字符串
*
* @param strXML
* @param str
* @return
*/
public static Boolean isContainStr(String strXML, String str) {
if (strXML == null) {
return false;
} else if (strXML.contains(str)) {
return true;
} else {
return false;
}
}
/**
* 判斷服務器返回的XML中是否有成功標誌
*
* @param strXML
* @return
*/
public static Boolean isReturnSuccess(String strXML) {
if (isContainStr(strXML, "<nisSuccess>1</nisSuccess>")) {
return true;
} else {
return false;
}
}
/**
* 解析XML
*
* @param is
* xml字節流
* @param clazz
* 字節碼 如:Object.class
* @param startName
* 開始位置
* @return 返回List列表
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List getParserFromXmlList(String XML, Class<?> clazz,
String startName) {
if (startName == null) {
startName = "item";
}
List list = null;
XmlPullParser parser = Xml.newPullParser();
Object object = null;
try {
parser.setInput(convert_StringTOInputStream(XML), "UTF-8");
// 事件類型
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<Object>();
break;
case XmlPullParser.START_TAG:
// 得到當前節點元素的名稱
String name = parser.getName();
if (startName.equals(name)) {
object = clazz.newInstance();
// 判斷標籤裏是否有屬性,若是有,則所有解析出來
int count = parser.getAttributeCount();
for (int i = 0; i < count; i++)
setXmlValue(object, parser.getAttributeName(i),
parser.getAttributeValue(i));
} else if (object != null) {
setXmlValue(object, name, parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if (startName.equals(parser.getName())) {
list.add(object);
object = null;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("xml pull error", e.toString());
}
return list;
}
/**
* 解析XML
*
* @param strXML
* xml字節流
* @param clazz
* 字節碼 如:Object.class
* @return 返回Object
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getParserFromXmlObject(String strXML, Class<?> clazz) {
XmlPullParser parser = Xml.newPullParser();
Object object = null;
List list = null;
Object subObject = null;
String subName = null;
try {
parser.setInput(convert_StringTOInputStream(strXML), "UTF-8");
// 事件類型
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
object = clazz.newInstance();
break;
case XmlPullParser.START_TAG:
// 得到當前節點元素的名稱
String name = parser.getName();
Field[] f = null;
if (subObject == null) {
f = object.getClass().getDeclaredFields();
// 判斷標籤裏是否有屬性,若是有,則所有解析出來
int count = parser.getAttributeCount();
for (int j = 0; j < count; j++)
setXmlValue(object, parser.getAttributeName(j),
parser.getAttributeValue(j));
} else {
f = subObject.getClass().getDeclaredFields();
}
for (int i = 0; i < f.length; i++) {
if (f[i].getName().equalsIgnoreCase(name)) {
// 判斷是否是List類型
if (f[i].getType().getName()
.equals("java.util.List")) {
Type type = f[i].getGenericType();
if (type instanceof ParameterizedType) {
// 得到泛型參數的實際類型
Class<?> subClazz = (Class<?>) ((ParameterizedType) type)
.getActualTypeArguments()[0];
subObject = subClazz.newInstance();
subName = f[i].getName();
// 判斷標籤裏是否有屬性,若是有,則所有解析出來
int count = parser.getAttributeCount();
for (int j = 0; j < count; j++)
setXmlValue(subObject,
parser.getAttributeName(j),
parser.getAttributeValue(j));
if (list == null) {
list = new ArrayList<Object>();
f[i].setAccessible(true);
f[i].set(object, list);
}
}
} else { // 普通屬性
if (subObject != null) {
setXmlValue(subObject, name,
parser.nextText());
} else {
setXmlValue(object, name, parser.nextText());
}
}
break;
}
}
break;
case XmlPullParser.END_TAG:
if (subObject != null
&& subName.equalsIgnoreCase(parser.getName())) {
list.add(subObject);
subObject = null;
subName = null;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("xml pull error", "exception");
e.printStackTrace();
}
return object;
}
/**
* 把xml標籤的值,轉換成對象裏屬性的值
*
* @param t
* 對象
* @param name
* xml標籤名
* @param value
* xml標籤名對應的值
*/
private static void setXmlValue(Object t, String name, String value) {
try {
Field[] f = t.getClass().getDeclaredFields();
for (int i = 0; i < f.length; i++) {
if (f[i].getName().equalsIgnoreCase(name)) {
f[i].setAccessible(true);
// 得到屬性類型
Class<?> fieldType = f[i].getType();
if (fieldType == String.class) {
f[i].set(t, value);
} else if (fieldType == Integer.TYPE) {
f[i].set(t, Integer.parseInt(value));
} else if (fieldType == Float.TYPE) {
f[i].set(t, Float.parseFloat(value));
} else if (fieldType == Double.TYPE) {
f[i].set(t, Double.parseDouble(value));
} else if (fieldType == Long.TYPE) {
f[i].set(t, Long.parseLong(value));
} else if (fieldType == Short.TYPE) {
f[i].set(t, Short.parseShort(value));
} else if (fieldType == Boolean.TYPE) {
f[i].set(t, Boolean.parseBoolean(value));
} else {
f[i].set(t, value);
}
}
}
} catch (Exception e) {
Log.e("xml error", e.toString());
}
}
/**
* 打開apk文件
*
* @param context
* @param file
*/
public static void APKopenFile(Context context, File file) {
Log.e("OpenFile", file.getName());
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
/**
* 複製舊文件並以新的名稱保存
*
* @param strOldFile
* @param strNewFile
* @return
*/
public static boolean copyFiletoFile(String strOldFile, String strNewFile) {
Boolean isSuccess = true;
File oldFile = new File(strOldFile);
if (!oldFile.exists()) {
System.err.println("copyFiletoFile:not exists");
return false;
} else if (!oldFile.canRead()) {
System.err.println("copyFiletoFile:can not read");
return false;
}
File newFile = new File(strNewFile);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
if (newFile.exists() && newFile.canWrite()) {
newFile.delete();
}
if (!newFile.exists()) {
try {
newFile.createNewFile();
} catch (IOException e) {
System.err.println("建立新文件出錯");
e.printStackTrace();
return false;
}
}
InputStream instream = null;
FileOutputStream outStream = null;
try {
instream = new FileInputStream(oldFile);
// 複製文件:從saveFile到tmpFile
outStream = new FileOutputStream(newFile);
int readSize = -1;
byte[] buf = new byte[1024];
while ((readSize = instream.read(buf)) != -1) {
outStream.write(buf, 0, readSize);
}
} catch (Exception e) {
isSuccess = false;
System.err.println("複製文件出錯!");
e.printStackTrace();
} finally {
try {
if (instream != null) {
instream.close();
}
outStream.flush();
if (outStream != null) {
outStream.close();
}
} catch (Exception e2) {
System.err.println("關閉流出錯!");
e2.printStackTrace();
}
}
return isSuccess;
}
/**
* 判斷sid是否有效
*
* @param strUid
* @return
*/
public static boolean isSidValidate(String strUid) {
Map<String, String> map = new HashMap<String, String>();
map.put("sid", strUid);
String strXml = Methods.getXML(ConstantURL.CHECK_SID_VALIDATE, map);
if (strXml == null) {
System.out.println("sid 失敗:xml null");
return false;
} else {
NormalResult nResult = (NormalResult) XmlParse.getXmlObject(strXml,
NormalResult.class);
if ("1".equals(nResult.getNisSuccess())) {
return true;
} else {
System.out.println("sid 失敗:" + nResult.getCinfo());
return false;
}
}
}
/**
* 判斷是否安裝某程序的包 "com.adobe.flashplayer"爲flash插件包名
*
* @param strPackageName
* @return
*/
public static boolean isExistedPackage(Context context,
String strPackageName) {
PackageManager pm = context.getPackageManager();
List<PackageInfo> infoList = pm
.getInstalledPackages(PackageManager.GET_SERVICES);
for (PackageInfo info : infoList) {
if (strPackageName.equals(info.packageName)) {
return true;
}
}
return false;
}
/**
* 返回一個打開視頻文件的Intent
*
* @param param
* @return
*/
public static Intent getVideoFileIntent(String param) {
Intent intent = new Intent("android.intent.action.VIEW");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("oneshot", 0);
intent.putExtra("configchange", 0);
Uri uri = Uri.parse(param);
intent.setDataAndType(uri, "video/*");
return intent;
}
/**
* 調用短信功能發送短信
*
* @param context
* @param phone
* @param content
*/
public static void createSMS(Context context, String phone, String content) {
Uri uri = Uri.parse("smsto:" + phone);
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", content);
context.startActivity(it);
}
/**
* 調出撥號功能打電話
*
* @param context
* @param phone
*/
public static void createTelCall(Context context, String phone) {
Uri uri = Uri.parse("tel:" + phone);
Intent it = new Intent(Intent.ACTION_DIAL, uri);
context.startActivity(it);
}
/**
* 將圖片變爲圓形
*
* @param x
* @param y
* @param image
* @param outerRadiusRat
* @return
*/
public static Bitmap createFramedPhoto(int x, int y, Bitmap image,
float outerRadiusRat) {
// 根據源文件新建一個darwable對象
Drawable imageDrawable = new BitmapDrawable(image);
// 新建一個新的輸出圖片
Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
// 新建一個矩形
RectF outerRect = new RectF(0, 0, x, y);
// 產生一個白色的圓角矩形
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);
// 將源圖片繪製到這個圓角矩形上 // 詳解見http://lipeng88213.iteye.com/blog/1189452
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
imageDrawable.setBounds(0, 0, x, y);
canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
imageDrawable.draw(canvas);
paint.setTextSize(10);
canvas.restore();
return output;
}
/**
* 將圖片變爲星形
*
* @param x
* @param y
* @param image
* @return
*/
public static Bitmap createStarPhoto(int x, int y, Bitmap image) {
// 根據源文件新建一個darwable對象
Drawable imageDrawable = new BitmapDrawable(image);
// 新建一個新的輸出圖片
Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
// 新建一個矩形
RectF outerRect = new RectF(0, 0, x, y);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
Path path = new Path();
// 繪製三角形
// path.moveTo(0, 0);
// path.lineTo(320, 250);
// path.lineTo(400, 0);
// 繪製正無邊形
long tmpX, tmpY;
path.moveTo(200, 200);// 此點爲多邊形的起點
for (int i = 0; i <= 5; i++) {
tmpX = (long) (200 + 200 * Math.sin((i * 72 + 36) * 2 * Math.PI
/ 360));
tmpY = (long) (200 + 200 * Math.cos((i * 72 + 36) * 2 * Math.PI
/ 360));
path.lineTo(tmpX, tmpY);
}
path.close(); // 使這些點構成封閉的多邊形
canvas.drawPath(path, paint);
// canvas.drawCircle(100, 100, 100, paint);
// 將源圖片繪製到這個圓角矩形上
// 產生一個紅色的圓角矩形
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
imageDrawable.setBounds(0, 0, x, y);
canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
imageDrawable.draw(canvas);
canvas.restore();
return output;
}
/**
* 保存bitmap爲bitName文件
*
* @param bitName
* @param mBitmap
* @param mQuality
* @throws IOException
*/
public static void saveMyBitmap(String bitName, Bitmap mBitmap, int mQuality)
throws IOException {
File f = new File(bitName);
f.createNewFile();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.JPEG, mQuality >= 100 ? 100
: mQuality, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 按正方形裁剪圖片
*
* @param bitmap
* @param newX
* @param newY
* @param newW
* @param newH
* @return
*/
public static Bitmap cropImage(Bitmap bitmap, int newX, int newY, int newW,
int newH) {
int w = bitmap.getWidth(); // 獲得圖片的寬,高
int h = bitmap.getHeight();
// newX、newY基於原圖,取長方形左上角x、y座標
// newW、newH基於原圖,裁剪的寬度和高度
// 下面這句是關鍵
return Bitmap.createBitmap(bitmap, newX, newY, newW, newH, null, false);
}
/**
* 獲取指定URL頁面的HTML格式代碼
*
* @param strUrl
* @return
*/
public static String getHtmlFromUrl(String strUrl) {
try {
// 根據http協議,要訪問服務器上的某個網頁,必須先創建一個鏈接,鏈接的參數爲一個URL
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 而後, //設置請求方式爲GET方式,就是至關於瀏覽器打開百度網頁
connection.setRequestMethod("GET");
// 接着設置超時時間爲5秒,5秒內若鏈接不上,則通知用戶網絡鏈接有問題
connection.setReadTimeout(3500);
// 若鏈接上以後,獲得網絡的輸入流,內容就是網頁源碼的字節碼
InputStream inStream = connection.getInputStream();
// 必須將其轉換爲字符串纔可以正確的顯示給用戶
ByteArrayOutputStream data = new ByteArrayOutputStream();// 新建一字節數組輸出流
byte[] buffer = new byte[1024];// 在內存中開闢一段緩衝區,接受網絡輸入流
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
data.write(buffer, 0, len);// 緩衝區滿了以後將緩衝區的內容寫到輸出流
}
inStream.close();
return new String(data.toByteArray(), "utf-8");// 最後能夠將獲得的輸出流轉成utf-8編碼的字符串,即可進一步處理
} catch (Exception e) {
return "";
}
}
/**
* 實現文本複製功能
*
* @param content
*/
public static void copy(String content, Context context) {
// 獲得剪貼板管理器
ClipboardManager cmb = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(content.trim());
}
/**
* 實現粘貼功能
*
* @param context
* @return
*/
public static String paste(Context context) {
// 獲得剪貼板管理器
ClipboardManager cmb = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
return cmb.getText().toString().trim();
}
/**
* 銷燬線程
*
* @param mThread
*/
public static void destroyThread(Thread mThread) {
if (mThread != null) {
try {
Log.i("destroyThread", "destroyThread開始");
mThread.interrupt();
System.gc();
System.runFinalization();
Log.i("destroyThread", "destroyThread結束");
} catch (Exception e) {
Log.i("destroyThread", "destroyThread異常");
}
}
}
/**
* 根據目標圖片大小返回縮放後的圖片
*
* @param imagePath
* 源圖片路徑
* @param intXdp
* 目標圖片寬度像素
* @param intYdp
* 目標圖片高度像素
* @return 目標圖片
*/
public static Bitmap getBitmap(String imagePath, int intXdp, int intYdp) {
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
int scale = 1;// 縮放倍數
while (true) {
if (options.outWidth / 2 >= intXdp
&& options.outHeight / 2 >= intYdp) {
options.outWidth /= 2;
options.outHeight /= 2;
scale++;
} else {
break;
}
}
Log.i("History", "inSampleSize=" + scale);
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imagePath, options);
}
/*
* public static String getStringCharactor(String strSource) { try {
* ParseEncoding parse; parse = new ParseEncoding(); byte[] bs =
* strSource.getBytes(); return parse.getEncoding(bs); } catch (Exception e)
* { } return null; }
*/
/**
* 驗證手機號
*
* @param strPhone
* @return
*/
public static boolean isRegexPhone(String strPhone) {
if (strPhone == null) {
return false;
}
Pattern p = Pattern
.compile("^((13[0-9])|(15[^4,\\D])|(18[0,2,5-9]))\\d{8}$");
Matcher m = p.matcher(strPhone);
System.out.println(m.matches() + "---");
return m.matches();
}
/**
* 開啓推送服務
*/
public static void startPushService(Activity activity) {
// Start the service
ServiceManager serviceManager = new ServiceManager(activity);
serviceManager.setNotificationIcon(R.drawable.ic_launcher);
serviceManager.startService();
}
/**
* 頁面跳轉
*/
public static void startActivity(Activity activity, Class<?> clazz,
Bundle mBundle, Boolean tfClose) {
Intent mIntent = new Intent(activity, clazz);
if (mBundle != null) {
mIntent.putExtras(mBundle);
}
mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(mIntent);
if (tfClose) {
activity.finish();
}
}
/**
* 檢測更新版本
*/
public static void checkVersionDialog(final Activity activity,
Boolean isStartCheck) {
final String strURL = Methods.CheckVersion(activity);
if (strURL.length() >= 10) {
final Dialog mDialog = new ModelDialog(activity,
R.layout.dialog_update_apk, R.style.Theme_dialog, true);
String strInfoXML = Methods.getXML(ConstantURL.UPDATE_INFO_APK,
null);
final String strUpdateInfo;
if (strInfoXML != null) {
APKUpdateInfo apkUpdateInfo = (APKUpdateInfo) XmlParse
.getXmlObject(strInfoXML, APKUpdateInfo.class);
strUpdateInfo = apkUpdateInfo.getCbeiz();
if (strUpdateInfo.length() >= 10) {
TextView tvContent = (TextView) mDialog
.findViewById(R.id.content_dialog_update_apk);
tvContent.setText(strUpdateInfo.substring(0,
strUpdateInfo.indexOf('W')));
TextView tvContent1 = (TextView) mDialog
.findViewById(R.id.content1_dialog_update_apk);
tvContent1.setText(strUpdateInfo.substring(strUpdateInfo
.indexOf('W') + 1));
}
} else {
strUpdateInfo = null;
}
Button btn_ok_update_apk = (Button) mDialog
.findViewById(R.id.btn_ok_update_apk);
btn_ok_update_apk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
Methods.startAPKdownLoadService(activity, strURL,
strUpdateInfo, true);
}
});
Button btn_cancel_update_apk = (Button) mDialog
.findViewById(R.id.btn_cancel_update_apk);
btn_cancel_update_apk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
new SharePreferenceUtil(activity).setPreferences(
CST_SharePreferName.NAME_SETTING,
CST_SharePreferName.UPDATE_DIALOG,
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date()));
}
});
mDialog.show();
} else if (Methods.netWorkType >= 1) {
if (!isStartCheck) {
Toast.makeText(activity, "恭喜,博餅已經是最新版本!", 0).show();
}
} else {
Toast.makeText(activity, "無網絡鏈接", 0).show();
}
}
// 讀取收件箱中指定號碼的最新一條短信
public static String readSMS(Activity activity, String strPhone) {
Cursor cursor = null;// 光標
/* cursor = activity.managedQuery(Uri.parse("content://sms/inbox"),
new String[] { "_id", "address", "body", "read" },
"address=? and read=?", new String[] { strPhone, "1" },
"date desc");*/
cursor = activity.managedQuery(Uri.parse("content://sms/inbox"),
new String[] { "_id", "address", "body", "read" },
"address=? ", new String[] { strPhone },
"date desc");
if (cursor != null) {// 若是短信爲已讀模式
cursor.moveToFirst();
if (cursor.moveToFirst()) {
return cursor.getString(cursor.getColumnIndex("body"));
}
}
return null;
}java
摘自http://blog.csdn.net/wanggsx918/article/details/19628105android