首页 > 代码库 > (转)android项目用到的公共类方法
(转)android项目用到的公共类方法
/**
* 直接下载图片并加载至控件(非异步加载)
*
* @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 = http://www.mamicode.com/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 = http://www.mamicode.com/new byte[BUFFER_SIZE];
int count = -1;
while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
data = http://www.mamicode.com/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 = http://www.mamicode.com/new byte[BUFFER_SIZE];
int count = -1;
while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
data = http://www.mamicode.com/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 = http://www.mamicode.com/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 = http://www.mamicode.com/(value << 4) + aChar - ‘0‘;
break;
case ‘a‘:
case ‘b‘:
case ‘c‘:
case ‘d‘:
case ‘e‘:
case ‘f‘:
value = http://www.mamicode.com/(value << 4) + 10 + aChar - ‘a‘;
break;
case ‘A‘:
case ‘B‘:
case ‘C‘:
case ‘D‘:
case ‘E‘:
case ‘F‘:
value = http://www.mamicode.com/(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 = http://www.mamicode.com/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;
}
摘自http://blog.csdn.net/wanggsx918/article/details/19628105