Last active
May 30, 2016 01:03
-
-
Save jp1017/9db07e79d45e2d6169a4 to your computer and use it in GitHub Desktop.
安卓新手必备的常用代码片段整理
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
/* | |
******************************* Copyright (c)*********************************\ | |
** | |
** (c) Copyright 2015, 蒋朋, china, qd. sd | |
** All Rights Reserved | |
** | |
** By(******公司) | |
** http://www.******.com | |
** | |
**-----------------------------------版本信息------------------------------------ | |
** 版 本: V0.1 | |
** | |
**------------------------------------------------------------------------------ | |
********************************End of Head************************************\ | |
*/ | |
package com.inst.instdriver.utils; | |
import android.annotation.TargetApi; | |
import android.app.Activity; | |
import android.app.ActivityManager; | |
import android.app.KeyguardManager; | |
import android.content.ComponentName; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.pm.PackageInfo; | |
import android.content.pm.PackageManager; | |
import android.graphics.Rect; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import android.net.Uri; | |
import android.net.wifi.WifiInfo; | |
import android.net.wifi.WifiManager; | |
import android.os.Build; | |
import android.os.Environment; | |
import android.os.PowerManager; | |
import android.provider.Settings; | |
import android.telephony.TelephonyManager; | |
import android.text.TextUtils; | |
import android.view.View; | |
import android.view.Window; | |
import android.view.WindowManager; | |
import android.view.inputmethod.InputMethodManager; | |
import android.widget.EditText; | |
import java.io.File; | |
import java.lang.reflect.Field; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.Properties; | |
import java.util.Set; | |
/** | |
* 文 件 名: AndroidCommonUtils | |
* 安卓新手必备的常用代码片段整理, | |
* 来源 :http://blog.csdn.net/zhaokaiqiang1992/article/details/44724057 | |
* http://blog.csdn.net/zhaokaiqiang1992/article/details/44724687 | |
* 创 建 人: 蒋朋 | |
* 邮 箱: [email protected] | |
* 博 客: http://jp1017.gitcafe.io | |
* 创建日期: 16-2-26 14:20 | |
*/ | |
public class AndroidCommonUtils { | |
/** | |
* bitmap 转化为字节数组 | |
* @param bitmap | |
* @return | |
*/ | |
public static byte[] formatBitmapToBytes(Bitmap bitmap){ | |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
bitmap.compress(Bitmap.CompressFormat.PNG,100,bos); | |
try { | |
bos.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return bos.toByteArray(); | |
} | |
/** | |
* 判断设备是否 root | |
* @return the boolean | |
*/ | |
public boolean isDeviceRooted() { | |
String su = "su"; | |
String[] locations = {"/sbin/", "/system/bin/", "/system/xbin/", "/system/sd/xbin/", "/system/bin/failsafe/", | |
"/data/local/xbin/", "/data/local/bin/", "/data/local/"}; | |
for (String location: locations) { | |
if (new File(location + su).exists()) { | |
return true; | |
} | |
} | |
return false; | |
} | |
/** | |
* 拨打电话 | |
* @param context | |
* @param phoneNumber | |
*/ | |
public static void call(Context context, String phoneNumber) { | |
context.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber))); | |
} | |
/** | |
* 跳转到拨号界面 | |
* @param context | |
* @param phoneNumber | |
*/ | |
public static void callDial(Context context, String phoneNumber) { | |
context.startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber))); | |
} | |
/** | |
* 发送短信 | |
* @param context | |
* @param phoneNumber | |
* @param content | |
*/ | |
public static void sendSms(Context context, String phoneNumber, String content) { | |
Uri uri = Uri.parse("smsto:" + (TextUtils.isEmpty(phoneNumber) ? "" : phoneNumber)); | |
Intent intent = new Intent(Intent.ACTION_SENDTO, uri); | |
intent.putExtra("sms_body", (TextUtils.isEmpty(content) ? "" : content)); | |
context.startActivity(intent); | |
} | |
/** | |
* 唤醒屏幕并解锁需要添加权限: | |
* <uses-permission android:name="android.permission.WAKE_LOCK" /> | |
* <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> | |
* @param context | |
*/ | |
public static void wakeUpAndUnlock(Context context) { | |
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); | |
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unlock"); | |
//解锁 | |
kl.disableKeyguard(); | |
//获取电源管理器对象 | |
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); | |
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright"); | |
wl.acquire();//点亮屏幕 | |
wl.release();//释放 | |
} | |
/** | |
* 判断当前app是否处于后台 | |
* 需要添加权限 <uses-permission android:name="android.permission.GET_TASKS" /> | |
* @param context | |
* @return | |
*/ | |
public static boolean isAppBackground(final Context context) { | |
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); | |
@SuppressWarnings("deprecation") | |
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1); | |
if (!tasks.isEmpty()) { | |
ComponentName topActivity = tasks.get(0).topActivity; | |
if (!topActivity.getPackageName().equals(context.getPackageName())) { | |
return true; | |
} | |
} | |
return false; | |
} | |
/** | |
* 判断当前手机是否处于锁屏(睡眠)状态 | |
* @param context | |
* @return | |
*/ | |
public static boolean isSleeping(Context context) { | |
KeyguardManager manager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); | |
return manager.inKeyguardRestrictedInputMode(); | |
} | |
/** | |
* 判断当前是否有网络连接 | |
* @param context | |
* @return | |
*/ | |
public static boolean isOnline(Context context) { | |
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo info = manager.getActiveNetworkInfo(); | |
if (info != null && info.isConnected()) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* 判断当前wifi是否可用 | |
* @param context | |
* @return | |
*/ | |
public static boolean isWifiConnected(Context context) { | |
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo info = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); | |
if (info.isConnected()) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* 安装apk | |
* @param context | |
* @param file | |
*/ | |
public static void installApk(Context context, File file) { | |
Intent intent = new Intent(); | |
intent.setAction("android.intent.action.VIEW"); | |
intent.setAction("android.intent.category.DEFAULT"); | |
intent.setType("application/vnd.android.package-archive"); | |
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); | |
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
context.startActivity(intent); | |
} | |
/** | |
* 判断当前设备是否为手机 | |
* @param context | |
* @return | |
*/ | |
public static boolean isPhone(Context context) { | |
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
if (manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) { | |
return false; | |
} else { | |
return true; | |
} | |
} | |
public static String getDeviceIMEI(Context context) { | |
String deviceId; | |
if (isPhone(context)) { | |
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
deviceId = manager.getDeviceId(); | |
} else { | |
deviceId = Settings.Secure.getString(context.getContentResolver(), | |
Settings.Secure.ANDROID_ID); | |
} | |
return deviceId; | |
} | |
/** | |
* 获取当前设备显示的宽度 | |
* @param context | |
* @return | |
*/ | |
@SuppressWarnings("deprecation") | |
public static int getDeviceWidth(Context context) { | |
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); | |
return manager.getDefaultDisplay().getWidth(); | |
} | |
/** | |
* 获取当前设备显示的高度 | |
* @param context | |
* @return | |
*/ | |
@SuppressWarnings("deprecation") | |
public static int getDeviceHeight(Context context) { | |
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); | |
return manager.getDefaultDisplay().getHeight(); | |
} | |
/** | |
* 获取当前设备的mac地址 | |
* @param context | |
* @return | |
*/ | |
public static String getMacAddress(Context context) { | |
String macAddress; | |
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); | |
WifiInfo info = manager.getConnectionInfo(); | |
macAddress = info.getMacAddress(); | |
if (null == macAddress) { | |
return ""; | |
} | |
macAddress = macAddress.replace(":", ""); | |
return macAddress; | |
} | |
/** | |
* 获取当前应用的版本号 | |
* @param context | |
* @return | |
*/ | |
public static String getAppVersion(Context context) { | |
String version = "0"; | |
try { | |
version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; | |
} catch (PackageManager.NameNotFoundException e) { | |
e.printStackTrace(); | |
} | |
return version; | |
} | |
/** | |
* 收集设备信息,用于信息统计分析 | |
* @param context | |
* @return | |
*/ | |
public static String collectDeviceInfoStr(Context context) { | |
Properties properties = collectDeviceInfo(context); | |
Set deviceInfos = properties.keySet(); | |
StringBuilder sb = new StringBuilder("{\n"); | |
for (Iterator iterator = deviceInfos.iterator(); iterator.hasNext() ;) { | |
Object item = iterator.next(); | |
sb.append("\t\t\t" + item + ":" + properties.get(item) + ", \n"); | |
} | |
sb.append("}"); | |
return sb.toString(); | |
} | |
public static Properties collectDeviceInfo(Context context) { | |
final String VERSION_NAME = "VERSION_NAME"; | |
final String VERSION_CODE = "VERSION_CODE"; | |
Properties mDeviceCrashInfo = new Properties(); | |
try { | |
PackageManager pm = context.getPackageManager(); | |
PackageInfo info = pm.getPackageInfo(context.getPackageName(), | |
PackageManager.GET_ACTIVITIES); | |
if (info != null) { | |
mDeviceCrashInfo.put(VERSION_NAME, info.versionName == null ? "not set" : info.versionName); | |
mDeviceCrashInfo.put(VERSION_CODE, info.versionCode); | |
} | |
} catch (PackageManager.NameNotFoundException e) { | |
e.printStackTrace(); | |
} | |
Field[] fields = Build.class.getDeclaredFields(); | |
for (Field field : fields) { | |
try { | |
field.setAccessible(true); | |
mDeviceCrashInfo.put(field.getName(), field.get(null)); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
return mDeviceCrashInfo; | |
} | |
/** | |
* 是否有SD卡 | |
* @return | |
*/ | |
public static boolean haveSDCard() { | |
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); | |
} | |
/** | |
* 动态隐藏软键盘 | |
* @param activity | |
*/ | |
@TargetApi(Build.VERSION_CODES.CUPCAKE) | |
public static void hideSoftInput(Activity activity) { | |
View view = activity.getWindow().peekDecorView(); | |
if (view != null) { | |
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); | |
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); | |
} | |
} | |
/** | |
* 动态隐藏软键盘 | |
* @param context | |
* @param edit | |
*/ | |
@TargetApi(Build.VERSION_CODES.CUPCAKE) | |
public static void hideSoftInput(Context context, EditText edit) { | |
edit.clearFocus(); | |
InputMethodManager inputmanger = (InputMethodManager) context | |
.getSystemService(Context.INPUT_METHOD_SERVICE); | |
inputmanger.hideSoftInputFromWindow(edit.getWindowToken(), 0); | |
} | |
/** | |
* 动态显示软键盘 | |
* @param context | |
* @param edit | |
*/ | |
@TargetApi(Build.VERSION_CODES.CUPCAKE) | |
public static void showSoftInput(Context context, EditText edit) { | |
edit.setFocusable(true); | |
edit.setFocusableInTouchMode(true); | |
edit.requestFocus(); | |
InputMethodManager inputManager = (InputMethodManager) context | |
.getSystemService(Context.INPUT_METHOD_SERVICE); | |
inputManager.showSoftInput(edit, 0); | |
} | |
/** | |
* 动态显示或者是隐藏软键盘 | |
* @param context | |
* @param edit | |
*/ | |
@TargetApi(Build.VERSION_CODES.CUPCAKE) | |
public static void toggleSoftInput(Context context, EditText edit) { | |
edit.setFocusable(true); | |
edit.setFocusableInTouchMode(true); | |
edit.requestFocus(); | |
InputMethodManager inputManager = (InputMethodManager) context | |
.getSystemService(Context.INPUT_METHOD_SERVICE); | |
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); | |
} | |
/** | |
* 主动回到home,后台运行 | |
* @param context | |
*/ | |
public static void goHome(Context context) { | |
Intent mHomeIntent = new Intent(Intent.ACTION_MAIN); | |
mHomeIntent.addCategory(Intent.CATEGORY_HOME); | |
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | |
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); | |
context.startActivity(mHomeIntent); | |
} | |
/** | |
* 获取状态栏高度,注意要在onWindowFocusChanged中调用,在onCreate中调用获取高度为0 | |
* @param activity | |
* @return | |
*/ | |
public static int getStatusBarHeight(Activity activity) { | |
Rect frame = new Rect(); | |
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); | |
return frame.top; | |
} | |
/** | |
* 获取状态栏和标题栏(ActionBar 或 ToolBar)的高度 | |
* @param activity | |
* @return 返回获取的高度,如果没有ActionBar,该高度就是状态栏高度,和上面的一样 | |
*/ | |
public static int getTopBarHeight(Activity activity) { | |
return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); | |
} | |
/** | |
* 获取MCC+MNC代码 (SIM卡运营商国家代码和运营商网络代码) | |
* @param context | |
* @return 返回获取的代码,中国移动:46000 46002, 中国联通:46001,中国电信:46003,仅当用户已在网络注册时有效 | |
*/ | |
public static String getNetWorkOperator(Context context) { | |
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
return manager.getNetworkOperator(); | |
} | |
/** | |
* 获取移动网络运营商的名字 | |
* @param context | |
* @return 返回获取到的移动网络运营商的名字,中国联通、中国移动、中国电信,仅当用户已在网络注册时有效, CDMA 可能会无效 | |
*/ | |
public static String getNetWorkOperatorName(Context context) { | |
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
return manager.getNetworkOperatorName(); | |
} | |
/** | |
* 获取移动终端类型 | |
* @param context | |
* @return PHONE_TYPE_NONE :0 手机制式未知, | |
* PHONE_TYPE_GSM :1 手机制式为GSM,移动和联通, | |
* PHONE_TYPE_CDMA :2 手机制式为CDMA,电信 | |
* PHONE_TYPE_SIP:3 | |
*/ | |
public static int getPhoneType(Context context) { | |
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
return manager.getPhoneType(); | |
} | |
public class Constants { | |
/** | |
* Unknown network class | |
*/ | |
public static final int NETWORK_CLASS_UNKNOWN = 0; | |
/** | |
* wifi net work | |
*/ | |
public static final int NETWORK_WIFI = 1; | |
/** | |
* "2G" networks | |
*/ | |
public static final int NETWORK_CLASS_2_G = 2; | |
/** | |
* "3G" networks | |
*/ | |
public static final int NETWORK_CLASS_3_G = 3; | |
/** | |
* "4G" networks | |
*/ | |
public static final int NETWORK_CLASS_4_G = 4; | |
} | |
/** | |
* 获取手机连接的网络类型(2G, 3G, 4G)对应的上面类的值 | |
* @param context | |
* @return 联通的3G为UMTS或HSDPA,移动和联通的2G为GPRS或EGDE,电信的2G为CDMA,电信的3G为EVDO | |
*/ | |
public static int getNetWorkClass(Context context) { | |
TelephonyManager telephonyManager = (TelephonyManager) context | |
.getSystemService(Context.TELEPHONY_SERVICE); | |
switch (telephonyManager.getNetworkType()) { | |
case TelephonyManager.NETWORK_TYPE_GPRS: | |
case TelephonyManager.NETWORK_TYPE_EDGE: | |
case TelephonyManager.NETWORK_TYPE_CDMA: | |
case TelephonyManager.NETWORK_TYPE_1xRTT: | |
case TelephonyManager.NETWORK_TYPE_IDEN: | |
return Constants.NETWORK_CLASS_2_G; | |
case TelephonyManager.NETWORK_TYPE_UMTS: | |
case TelephonyManager.NETWORK_TYPE_EVDO_0: | |
case TelephonyManager.NETWORK_TYPE_EVDO_A: | |
case TelephonyManager.NETWORK_TYPE_HSDPA: | |
case TelephonyManager.NETWORK_TYPE_HSUPA: | |
case TelephonyManager.NETWORK_TYPE_HSPA: | |
case TelephonyManager.NETWORK_TYPE_EVDO_B: | |
case TelephonyManager.NETWORK_TYPE_EHRPD: | |
case TelephonyManager.NETWORK_TYPE_HSPAP: | |
return Constants.NETWORK_CLASS_3_G; | |
case TelephonyManager.NETWORK_TYPE_LTE: | |
return Constants.NETWORK_CLASS_4_G; | |
default: | |
return Constants.NETWORK_CLASS_UNKNOWN; | |
} | |
} | |
/** | |
* 获取手机连接的网络类型(wifi, 2G, 3G, 4G) | |
* @param context | |
* @return | |
*/ | |
public static int getNetWorkStatus(Context context) { | |
int netWorkType = Constants.NETWORK_CLASS_UNKNOWN; | |
ConnectivityManager connectivityManager = (ConnectivityManager) context | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); | |
if (networkInfo != null && networkInfo.isConnected()) { | |
int type = networkInfo.getType(); | |
if (type == ConnectivityManager.TYPE_WIFI) { | |
netWorkType = Constants.NETWORK_WIFI; | |
} else if (type == ConnectivityManager.TYPE_MOBILE) { | |
netWorkType = getNetWorkClass(context); | |
} | |
} | |
return netWorkType; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment