Last active
December 31, 2015 19:19
-
-
Save AvatarQing/8032935 to your computer and use it in GitHub Desktop.
Android常用功能函数
This file contains 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
public class Const { | |
/** 编码 */ | |
public static final String ENCODING = "utf-8"; | |
/** GooglePlay包名 */ | |
public static final String GOOGLE_PLAY_PACKAGE_NAME = "com.android.vending"; | |
/** GooglePlay地址http前缀 */ | |
public static final String GOOGLE_PLAY_PREFFIX_HTTP = "http://play.google.com/store/apps/details?id="; | |
/** GooglePlay地址https前缀 */ | |
public static final String GOOGLE_PLAY_PREFFIX_HTTPS = "https://play.google.com/store/apps/details?id="; | |
/** GooglePlay地址market前缀 */ | |
public static final String GOOGLE_PLAY_PREFFIX_MARKET = "market://details?id="; | |
/** 网络请求参数键值。系统版本。 */ | |
public static final String PARAM_OS_VERSION = "os_version"; | |
/** 网络请求参数键值。国家。 */ | |
public static final String PARAM_COUNTRY = "country"; | |
/** 网络请求参数键值。语言。 */ | |
public static final String PARAM_LANGUAGE = "language"; | |
/** 网络请求参数键值。制造商。 */ | |
public static final String PARAM_MANUFACTURE = "manufacture"; | |
/** 网络请求参数键值。手机型号。 */ | |
public static final String PARAM_PHONE_MODEL = "phone_model"; | |
/** 网络请求参数键值。网络连接类型。 */ | |
public static final String PARAM_CONNECTION_TYPE = "connection_type"; | |
/** 网络请求参数键值。包名。 */ | |
public static final String PARAM_PACKAGE_NAME = "package_name"; | |
/** 网络请求参数键值。屏幕分辨率。 */ | |
public static final String PARAM_SCREEN_SIZE = "screen_size"; | |
/** 网络请求参数键值。屏幕密度。 */ | |
public static final String PARAM_SCREEN_DP = "screen_dp"; | |
} |
This file contains 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
public class EncrypteUtil { | |
/** | |
* 加密文件 | |
* | |
* @param secretKey | |
* 密钥 | |
* @param sourceFile | |
* 源文件 | |
* @param outFile | |
* 加密后的文件 | |
* @throws Exception | |
*/ | |
public static void encryptFile(String secretKey, File sourceFile, | |
File outFile) throws Exception { | |
FileInputStream fis = new FileInputStream(sourceFile); | |
FileOutputStream fos = new FileOutputStream(outFile); | |
// Generate key | |
byte[] key = getRawKey(secretKey.getBytes()); | |
SecretKeySpec sks = new SecretKeySpec(key, "AES"); | |
// Create cipher | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(Cipher.ENCRYPT_MODE, sks); | |
// Wrap the output stream | |
CipherOutputStream cos = new CipherOutputStream(fos, cipher); | |
// Write bytes | |
int length; | |
byte[] buffer = new byte[1024]; | |
while ((length = fis.read(buffer)) != -1) { | |
cos.write(buffer, 0, length); | |
} | |
// Flush and close streams. | |
cos.flush(); | |
cos.close(); | |
fis.close(); | |
} | |
/** | |
* 解密文件 | |
* | |
* @param secretKey | |
* 密钥 | |
* @param sourceFile | |
* 源文件路径 | |
* @param outFile | |
* 加密后的文件保存的路径 | |
* @throws Exception | |
*/ | |
public static void decryptFile(String secretKey, File sourceFile, | |
File outFile) throws Exception { | |
FileInputStream fis = new FileInputStream(sourceFile); | |
FileOutputStream fos = new FileOutputStream(outFile); | |
// Generate key | |
byte[] key = getRawKey(secretKey.getBytes()); | |
SecretKeySpec sks = new SecretKeySpec(key, "AES"); | |
// Create cipher | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(Cipher.DECRYPT_MODE, sks); | |
// Wrap the output stream | |
CipherInputStream cis = new CipherInputStream(fis, cipher); | |
// Write bytes | |
int length; | |
byte[] buffer = new byte[1024]; | |
while ((length = cis.read(buffer)) != -1) { | |
fos.write(buffer, 0, length); | |
} | |
// Flush and close streams. | |
fos.flush(); | |
fos.close(); | |
cis.close(); | |
} | |
/** | |
* 加密文本 | |
* | |
* @param seed | |
* 明文密码 | |
* @param content | |
* 要加密的文本 | |
*/ | |
public static String encryptText(String seed, String content) | |
throws Exception { | |
byte[] result = encryptInternal(Cipher.ENCRYPT_MODE, seed, | |
content.getBytes()); | |
return toHex(result); | |
} | |
/** | |
* 加密文本 | |
* | |
* @param seed | |
* 明文密码 | |
* @param encryptedContent | |
* 加密后的文本 | |
*/ | |
public static String decryptText(String seed, String encryptedContent) | |
throws Exception { | |
byte[] enc = toByte(encryptedContent); | |
byte[] result = encryptInternal(Cipher.DECRYPT_MODE, seed, enc); | |
return new String(result); | |
} | |
/** | |
* 加密/解密 | |
* | |
* @param encryptMode | |
* 加密模式 | |
* @param secretKey | |
* 密钥 | |
* @param content | |
* 源文本 | |
*/ | |
private static byte[] encryptInternal(int encryptMode, String secretKey, | |
byte[] content) throws Exception { | |
// Generate key | |
byte[] key = getRawKey(secretKey.getBytes()); | |
SecretKeySpec sks = new SecretKeySpec(key, "AES"); | |
// Create cipher | |
Cipher cipher = Cipher.getInstance("AES"); | |
cipher.init(encryptMode, sks); | |
byte[] encrypted = cipher.doFinal(content); | |
return encrypted; | |
} | |
/** | |
* 根据明文密码生成加密了的加密密码 | |
*/ | |
public static byte[] getRawKey(byte[] seed) throws Exception { | |
KeyGenerator kgen = KeyGenerator.getInstance("AES"); | |
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); | |
sr.setSeed(seed); | |
kgen.init(128, sr); // 192 and 256 bits may not be available | |
SecretKey skey = kgen.generateKey(); | |
byte[] raw = skey.getEncoded(); | |
return raw; | |
} | |
/** | |
* 十六进制数的字符串转换为字节数组 | |
* | |
* @param hexString | |
* 字符串 | |
*/ | |
public static byte[] toByte(String hexString) { | |
int len = hexString.length() / 2; | |
byte[] result = new byte[len]; | |
for (int i = 0; i < len; i++) { | |
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), | |
16).byteValue(); | |
} | |
return result; | |
} | |
/** | |
* 二进制的字节数组转换为十六进制数的字符串 | |
*/ | |
public static String toHex(byte[] buf) { | |
if (buf == null) { | |
return ""; | |
} | |
final String HEX = "0123456789ABCDEF"; | |
StringBuffer result = new StringBuffer(2 * buf.length); | |
for (int i = 0; i < buf.length; i++) { | |
result.append(HEX.charAt((buf[i] >> 4) & 0x0f)).append( | |
HEX.charAt(buf[i] & 0x0f)); | |
} | |
return result.toString(); | |
} | |
} |
This file contains 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
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Locale; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.message.BasicNameValuePair; | |
import android.content.Context; | |
import android.content.pm.PackageInfo; | |
import android.content.pm.PackageManager; | |
import android.content.pm.PackageManager.NameNotFoundException; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.os.Build; | |
import android.telephony.TelephonyManager; | |
import android.util.DisplayMetrics; | |
import android.util.Log; | |
import android.view.WindowManager; | |
import android.widget.Toast; | |
import com.phonetools.appmanager.MyApp; | |
public class Utils { | |
private static final String TAG = "Utils"; | |
private static Toast TOAST = null; | |
public static void showLongToast(Context context, String text) { | |
if (TOAST != null) { | |
TOAST.cancel(); | |
} | |
TOAST = Toast.makeText(context, text, Toast.LENGTH_LONG); | |
TOAST.show(); | |
} | |
public static void showShortToast(Context context, String text) { | |
if (TOAST != null) { | |
TOAST.cancel(); | |
} | |
TOAST = Toast.makeText(context, text, Toast.LENGTH_SHORT); | |
TOAST.show(); | |
} | |
/** 判断应用是否已经安装 */ | |
public static boolean isAppInstall(Context context, String packageName) { | |
boolean installed = false; | |
try { | |
PackageInfo packageInfo = context.getPackageManager() | |
.getPackageInfo(packageName, 0); | |
if (packageInfo != null) { | |
installed = true; | |
} | |
} catch (NameNotFoundException e) { | |
e.printStackTrace(); | |
} | |
return installed; | |
} | |
/** 判断外部存储器是否可用 */ | |
public static boolean isExternalStorageAvaliable() { | |
return Environment.getExternalStorageState().equals( | |
Environment.MEDIA_MOUNTED); | |
} | |
/** 判断网络是否已经连接 */ | |
public static final boolean isNetworkConnected(Context context) { | |
boolean result = false; | |
int ansPermission = context | |
.checkCallingOrSelfPermission(android.Manifest.permission.ACCESS_NETWORK_STATE); | |
int internetPermission = context | |
.checkCallingOrSelfPermission(android.Manifest.permission.INTERNET); | |
if (ansPermission == PackageManager.PERMISSION_GRANTED | |
&& internetPermission == PackageManager.PERMISSION_GRANTED) { | |
if (context != null) { | |
ConnectivityManager cm = (ConnectivityManager) context | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo networkInfo = cm.getActiveNetworkInfo(); | |
if (networkInfo != null) { | |
int type = networkInfo.getType(); | |
switch (type) { | |
case ConnectivityManager.TYPE_MOBILE: | |
case ConnectivityManager.TYPE_WIFI: | |
case ConnectivityManager.TYPE_WIMAX: | |
if (networkInfo.isAvailable() | |
&& networkInfo.isConnected()) { | |
result = true; | |
} | |
break; | |
} | |
} | |
} | |
} | |
return result; | |
} | |
/** 获取制造商信息 */ | |
public static String getManufacture() { | |
return Build.MANUFACTURER; | |
} | |
/** 获取网络连接类型 */ | |
public static String getConnectionType(Context context) { | |
String retConnectType = null; | |
if (null != context) { | |
ConnectivityManager cm = (ConnectivityManager) context | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo ni = cm.getActiveNetworkInfo(); | |
if ((ni != null) && (ni.isConnected())) { | |
retConnectType = ni.getTypeName(); | |
} else { | |
retConnectType = ""; | |
} | |
} else { | |
retConnectType = ""; | |
Log.e(TAG, | |
"Failed to get network operator , did you forgot to init context?"); | |
} | |
return retConnectType; | |
} | |
/** | |
* 获取屏幕尺寸 | |
* | |
* @return 返回如 480*800 | |
*/ | |
public static String getScreenSize(Context context) { | |
String screenSize = null; | |
if (null != context) { | |
DisplayMetrics outMetrics = new DisplayMetrics(); | |
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)) | |
.getDefaultDisplay().getMetrics(outMetrics); | |
screenSize = outMetrics.widthPixels + "*" + outMetrics.heightPixels; | |
} else { | |
screenSize = ""; | |
Log.e(TAG, | |
"Failed to get screen size, did you forgot to init context?"); | |
} | |
return screenSize; | |
} | |
public static String getPackageName(Context context) { | |
String retPackString = null; | |
if (null != context) { | |
retPackString = context.getPackageName(); | |
} else { | |
retPackString = ""; | |
Log.e(TAG, | |
"Failed to get package name , did you forgot to init context?"); | |
} | |
return retPackString; | |
} | |
/** 获取语言 */ | |
public static String getLanguage() { | |
return Locale.getDefault().getDisplayLanguage(); | |
} | |
/** 获取国家 */ | |
public static String getCountry() { | |
return Locale.getDefault().getDisplayCountry(); | |
} | |
/** 获取手机型号 */ | |
public static String getPhoneModel() { | |
return Build.MODEL; | |
} | |
/** 获取系统版本 */ | |
public static String getOsVersion() { | |
return Build.VERSION.SDK_INT + ""; | |
} | |
/** 获取屏幕密度 */ | |
public static String getScreenDp(Context context) { | |
String retDpString = null; | |
if (null != context) { | |
DisplayMetrics metrics = context.getResources().getDisplayMetrics(); | |
retDpString = metrics.density + ""; | |
} else { | |
retDpString = ""; | |
Log.e(TAG, | |
"Failed to get screen , did you forgot to init context?"); | |
} | |
return retDpString; | |
} | |
/** 返回设备的IMEI或MEID号 */ | |
public static String getImei(Context context) { | |
String retImei = ""; | |
if (null != context) { | |
TelephonyManager telMgr = (TelephonyManager) context | |
.getSystemService(Context.TELEPHONY_SERVICE); | |
if (null != telMgr) { | |
retImei = telMgr.getDeviceId(); | |
} | |
} else { | |
Log.e(TAG, "Failed to get imei , did you forgot to init context?"); | |
} | |
return retImei; | |
} | |
/** 返回设备的用户识别码(IMSI) */ | |
public static String getImsi(Context context) { | |
String retImsi = ""; | |
if (null != context) { | |
TelephonyManager telMgr = (TelephonyManager) context | |
.getSystemService(Context.TELEPHONY_SERVICE); | |
if (null != telMgr) { | |
retImsi = telMgr.getSubscriberId(); | |
} | |
} else { | |
Log.e(TAG, "Failed to get imsi, did you forgot to init context?"); | |
} | |
return retImsi; | |
} | |
/** | |
* 追加设备信息参数(针对http post请求) | |
* | |
* @param params | |
* 在该参数列表后追加设备信息参数。如果给出的参数列表为null,则创建一个新的参数列表返回 | |
*/ | |
public static List<NameValuePair> buildDeviceInfoParams(Context context, | |
List<NameValuePair> params) { | |
// 将部分设备信息一并传给服务器,以便服务器分析利用 | |
if (params == null) { | |
params = new ArrayList<NameValuePair>(); | |
} | |
params.add(new BasicNameValuePair(Const.PARAM_OS_VERSION, Utils | |
.getOsVersion())); | |
params.add(new BasicNameValuePair(Const.PARAM_COUNTRY, Utils | |
.getCountry())); | |
params.add(new BasicNameValuePair(Const.PARAM_LANGUAGE, Utils | |
.getLanguage())); | |
params.add(new BasicNameValuePair(Const.PARAM_MANUFACTURE, Utils | |
.getManufacture())); | |
params.add(new BasicNameValuePair(Const.PARAM_PHONE_MODEL, Utils | |
.getPhoneModel())); | |
params.add(new BasicNameValuePair(Const.PARAM_CONNECTION_TYPE, Utils | |
.getConnectionType(context))); | |
params.add(new BasicNameValuePair(Const.PARAM_PACKAGE_NAME, Utils | |
.getPackageName(context))); | |
params.add(new BasicNameValuePair(Const.PARAM_SCREEN_SIZE, Utils | |
.getScreenSize(context))); | |
params.add(new BasicNameValuePair(Const.PARAM_SCREEN_DP, Utils | |
.getScreenDp(context))); | |
return params; | |
} | |
/** 给指定字符串进行MD5加密 */ | |
public static String generateMD5DigestWithEncoder(String text) { | |
String result = null; | |
try { | |
MessageDigest md5 = MessageDigest.getInstance("md5"); | |
md5.update(text.getBytes(Const.ENCODING)); | |
byte[] digest = md5.digest(); | |
result = new String(Base64.encode(digest, Base64.DEFAULT), | |
Const.ENCODING); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
return result; | |
} | |
/**用第三方程序打开指定链接*/ | |
public static void openLink(Context context, String link) { | |
if(!TextUtils.isEmpty(link)){ | |
Intent intent = new Intent(); | |
intent.setAction(Intent.ACTION_VIEW); | |
intent.setData(Uri.parse(link)); | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
// 判断是否是GooglePlay的链接 | |
if (link.startsWith(Const.GOOGLE_PLAY_PREFFIX_HTTP) | |
|| link.startsWith(Const.GOOGLE_PLAY_PREFFIX_HTTPS) | |
|| link.startsWith(Const.GOOGLE_PLAY_PREFFIX_MARKET)) { | |
// 如果安装了GooglePlay | |
if (isAppInstall(context, Const.GOOGLE_PLAY_PACKAGE_NAME)) { | |
// 就用GooglePlay打开链接 | |
intent.setPackage(Const.GOOGLE_PLAY_PACKAGE_NAME); | |
} | |
} | |
try { | |
context.startActivity(intent); | |
} catch (Exception e) { | |
// 做一个异常捕获,防止没有第三方程序可以打开这个链接 | |
e.printStackTrace(); | |
} | |
} | |
} | |
/** | |
* 分享一段文字 | |
* | |
* @param context | |
* 上下文环境,启动Activity用 | |
* @param subject | |
* 分享文案的主题 | |
* @param text | |
* 分享的文字内容 | |
* */ | |
public static void shareText(Context context, String subject, String text) { | |
Intent intent = new Intent(Intent.ACTION_SEND); | |
intent.setType("text/plain"); | |
intent.putExtra(Intent.EXTRA_SUBJECT, subject); | |
intent.putExtra(Intent.EXTRA_TEXT, text); | |
try { | |
intent = Intent.createChooser(intent, subject); | |
if (intent != null) { | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
context.startActivity(intent); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* 分享图片 | |
* | |
* @param context | |
* 上下文环境 | |
* | |
* @param uri | |
* 图片地址 | |
*/ | |
public static void shareImage(Context context, Uri uri) { | |
if (uri != null) { | |
Intent shareIntent = new Intent(); | |
shareIntent.setAction(Intent.ACTION_SEND); | |
shareIntent.setType("image/*"); | |
shareIntent.putExtra(Intent.EXTRA_STREAM, uri); | |
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
try { | |
context.startActivity(Intent.createChooser(shareIntent, | |
context.getString(R.string.action_share))); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return; | |
} | |
} | |
} | |
/** | |
* 调用第三方邮件程序发送文本内容的邮件 | |
* | |
* @param context | |
* 上下文环境,用于启动Activity | |
* @param receivers | |
* 邮件接收者,可以是多个 | |
* @param subject | |
* 邮件主题 | |
* @param content | |
* 邮件的文本内容 | |
* */ | |
public static void sendTextEmail(Context context, String[] receivers, | |
String subject, String content) { | |
// 将反馈内容发送邮件给作者 | |
Intent intent = new Intent(Intent.ACTION_SEND); | |
intent.setType("message/rfc822"); | |
// 设置邮件收件人 | |
intent.putExtra(Intent.EXTRA_EMAIL, receivers); | |
// 设置邮件标题 | |
intent.putExtra(Intent.EXTRA_SUBJECT, subject); | |
// 设置邮件内容 | |
intent.putExtra(Intent.EXTRA_TEXT, content); | |
// 调用系统的邮件系统 | |
intent = Intent.createChooser(intent, subject); | |
try { | |
if (intent != null) { | |
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
context.startActivity(intent); | |
} | |
} catch (Exception e) { | |
// 如果设备没有安装可以发送邮件的程序,就会出错,所以手动捕获以下 | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* 复制文件 | |
* | |
* @param sourcefile | |
* 源文件 | |
* @param destFile | |
* 目标文件 | |
* @return 复制成功返回true,失败返回false | |
*/ | |
public static boolean copyFile(File sourcefile, File destFile) { | |
boolean result = false; | |
if (sourcefile != null && destFile != null) { | |
InputStream in = null; | |
OutputStream out = null; | |
try { | |
in = new FileInputStream(sourcefile); | |
out = new FileOutputStream(destFile); | |
// copy file | |
byte[] buffer = new byte[1024]; | |
int read; | |
while ((read = in.read(buffer)) != -1) { | |
out.write(buffer, 0, read); | |
} | |
in.close(); | |
in = null; | |
out.flush(); | |
out.close(); | |
out = null; | |
result = true; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
result = false; | |
} | |
} | |
return result; | |
} | |
/** 删除一个文件或目录下所有文件 */ | |
public static void deleteFileOrDir(File file) { | |
if (file != null) { | |
if (file.isFile()) { | |
file.delete(); | |
return; | |
} | |
if (file.isDirectory()) { | |
File[] childrenFiles = file.listFiles(); | |
if (childrenFiles != null && childrenFiles.length > 0) { | |
for (File child : childrenFiles) { | |
deleteFileOrDir(child); | |
} | |
} | |
file.delete(); | |
} | |
} | |
} | |
/** 判断移动网络是否已经连接 */ | |
public static final boolean isMobileNetworkConnected(Context context) { | |
ConnectivityManager mConnectivityManager = (ConnectivityManager) context | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
try { | |
Class<?> cmClass = mConnectivityManager.getClass(); | |
Class<?>[] argClasses = new Class[] { Boolean.class }; | |
// 反射ConnectivityManager中hide的方法setMobileDataEnabled,可以开启和关闭GPRS网络 | |
Method methodSetMobileDataEnabled = cmClass.getMethod( | |
"setMobileDataEnabled", argClasses); | |
methodSetMobileDataEnabled.invoke(mConnectivityManager, enable); | |
Log.d(TAG, "setMobileDataEnabled:" + enable); | |
} catch (Exception e) { | |
Log.d(TAG, "reflect to MobileDataEnabled failed"); | |
e.printStackTrace(); | |
} | |
} | |
public class Utils{ | |
/** | |
* 利用反射将父类mShowing变量设为false,表示对话框已关闭,父类不会再因为按了按钮而关闭对话框 | |
* | |
* @param isShown | |
* true表示点击按钮时对话框不会关闭,false为点击按钮对话框会关闭 | |
*/ | |
public static void setWindowShownWhenClickedButton(Dialog dialog, | |
boolean isShown) { | |
try { | |
Field field = dialog.getClass().getSuperclass() | |
.getDeclaredField("mShowing"); | |
field.setAccessible(true); | |
// 将mShowing变量设为false,表示对话框已关闭 | |
field.set(dialog, !isShown); | |
} catch (Exception e) { | |
} | |
} | |
public static void setDialogDismiss(Dialog dialog) { | |
setWindowShownWhenClickedButton(dialog, false); | |
dialog.dismiss(); | |
} | |
public static void setDialogStayShown(Dialog dialog) { | |
setWindowShownWhenClickedButton(dialog, true); | |
} | |
/** | |
* 获取默认SharedPreferences的布尔值 | |
* | |
* @param context | |
* 上下文环境 | |
* @param key | |
* 键值 | |
* @param defValue | |
* 默认值 | |
*/ | |
public static boolean getPrefBoolean(Context context, String key, | |
boolean defValue) { | |
return PreferenceManager.getDefaultSharedPreferences(context) | |
.getBoolean(key, defValue); | |
} | |
/** | |
* 获取默认SharedPreferences的字符串值 | |
* | |
* @param context | |
* 上下文环境 | |
* @param key | |
* 键值 | |
* @param defValue | |
* 默认值 | |
*/ | |
public static String getPrefString(Context context, String key, | |
String defValue) { | |
return PreferenceManager.getDefaultSharedPreferences(context) | |
.getString(key, defValue); | |
} | |
/** | |
* 快速复制文件 | |
* | |
* @param source | |
* 源文件 | |
* @param target | |
* 目标文件 | |
*/ | |
public static void nioTransferCopy(File source, File target) { | |
FileChannel in = null; | |
FileChannel out = null; | |
FileInputStream inStream = null; | |
FileOutputStream outStream = null; | |
try { | |
inStream = new FileInputStream(source); | |
outStream = new FileOutputStream(target); | |
in = inStream.getChannel(); | |
out = outStream.getChannel(); | |
in.transferTo(0, in.size(), out); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
try { | |
if (in != null) { | |
in.close(); | |
} | |
if (out != null) { | |
out.close(); | |
} | |
if (inStream != null) { | |
inStream.close(); | |
} | |
if (outStream != null) { | |
outStream.close(); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
/** | |
* 获取当前可用内存大小 | |
* | |
* @param context | |
* 上下文 | |
* @return 内存大小,单位字节 | |
*/ | |
public static long getAvailableMemory(Context context) { | |
ActivityManager am = (ActivityManager) context | |
.getSystemService(Context.ACTIVITY_SERVICE); | |
MemoryInfo mi = new MemoryInfo(); | |
am.getMemoryInfo(mi); | |
return mi.availMem; | |
} | |
/** | |
* 获取总的内存大小 | |
* | |
* @param context | |
* 上下文 | |
* @return 内存大小,单位字节 | |
*/ | |
@SuppressLint("NewApi") | |
public static long getTotalMemory(Context context) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { | |
ActivityManager am = (ActivityManager) context | |
.getSystemService(Context.ACTIVITY_SERVICE); | |
MemoryInfo mi = new MemoryInfo(); | |
am.getMemoryInfo(mi); | |
return mi.totalMem; | |
} else { | |
String str1 = "/proc/meminfo";// 系统内存信息文件 | |
String str2; | |
String[] arrayOfString; | |
long initial_memory = 0; | |
try { | |
FileReader localFileReader = new FileReader(str1); | |
BufferedReader localBufferedReader = new BufferedReader( | |
localFileReader, 8192); | |
// 读取meminfo第一行,系统总内存大小 | |
str2 = localBufferedReader.readLine(); | |
arrayOfString = str2.split("\\s+"); | |
for (String num : arrayOfString) { | |
Log.i(str2, num + "\t"); | |
} | |
// 获得系统总内存,单位是KB | |
initial_memory = Long.valueOf(arrayOfString[1]).longValue() * 1024; | |
localBufferedReader.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return initial_memory; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment