拨打电话

public static void call(Context context, String phoneNumber) {

     context.startActivity( new Intent(Intent.ACTION_CALL, Uri.parse( "tel:" + phoneNumber)));

   }

跳转至拨号界面

public static void callDial(Context context, String phoneNumber) {

     context.startActivity( new Intent(Intent.ACTION_DIAL, Uri.parse( "tel:" + phoneNumber)));

}

发送短信

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);

   }

唤醒屏幕并解锁

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对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag 

     PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright" ); 

     //点亮屏幕 

     wl.acquire(); 

     //释放 

     wl.release(); 

   }

需要添加权限

<uses-permission android:name= "android.permission.WAKE_LOCK" />

<uses-permission android:name= "android.permission.DISABLE_KEYGUARD" />

判断当前App处于前台还是后台状态

public static boolean isApplicationBackground( final Context context) {

     ActivityManager am = (ActivityManager) context

         .getSystemService(Context.ACTIVITY_SERVICE);

     @SuppressWarnings ( "deprecation" )

     List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(  );

     if (!tasks.isEmpty()) {

       ComponentName topActivity = tasks.get(  ).topActivity;

       if (!topActivity.getPackageName().equals(context.getPackageName())) {

         return true ;

       }

     }

     return false ;

   }

需要添加权限

<uses-permission

    android:name= "android.permission.GET_TASKS" /

判断当前手机是否处于锁屏(睡眠)状态

public static boolean isSleeping(Context context) {

     KeyguardManager kgMgr = (KeyguardManager) context

         .getSystemService(Context.KEYGUARD_SERVICE);

     boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();

     return isSleeping;

   }

判断当前是否有网络连接

public static boolean isOnline(Context context) {

     ConnectivityManager manager = (ConnectivityManager) context

         .getSystemService(Activity.CONNECTIVITY_SERVICE);

     NetworkInfo info = manager.getActiveNetworkInfo();

     if (info != null && info.isConnected()) {

       return true ;

     }

     return false ;

   }

判断当前是否是WIFI连接状态

public static boolean isWifiConnected(Context context) {

   ConnectivityManager connectivityManager = (ConnectivityManager) context

       .getSystemService(Context.CONNECTIVITY_SERVICE);

   NetworkInfo wifiNetworkInfo = connectivityManager

       .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

   if (wifiNetworkInfo.isConnected()) {

     return true ;

   }

   return false ;

}

安装APK

public static void installApk(Context context, File file) {

   Intent intent = new Intent();

   intent.setAction( "android.intent.action.VIEW" );

   intent.addCategory( "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);

}

判断当前设备是否为手机

public static boolean isPhone(Context context) {

   TelephonyManager telephony = (TelephonyManager) context

       .getSystemService(Context.TELEPHONY_SERVICE);

   if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {

     return false ;

   } else {

     return true ;

   }

}

获取当前设备宽高,单位px

@SuppressWarnings ( "deprecation" )

public static int getDeviceWidth(Context context) {

   WindowManager manager = (WindowManager) context

       .getSystemService(Context.WINDOW_SERVICE);

   return manager.getDefaultDisplay().getWidth();

}

@SuppressWarnings ( "deprecation" )

public static int getDeviceHeight(Context context) {

   WindowManager manager = (WindowManager) context

       .getSystemService(Context.WINDOW_SERVICE);

   return manager.getDefaultDisplay().getHeight();

}

获取当前设备的IMEI,需要与上面的isPhone()一起使用

@TargetApi (Build.VERSION_CODES.CUPCAKE)

public static String getDeviceIMEI(Context context) {

   String deviceId;

   if (isPhone(context)) {

     TelephonyManager telephony = (TelephonyManager) context

         .getSystemService(Context.TELEPHONY_SERVICE);

     deviceId = telephony.getDeviceId();

   } else {

     deviceId = Settings.Secure.getString(context.getContentResolver(),

         Settings.Secure.ANDROID_ID);

   }

   return deviceId;

}

获取当前设备的MAC地址

public static String getMacAddress(Context context) {

   String macAddress;

   WifiManager wifi = (WifiManager) context

       .getSystemService(Context.WIFI_SERVICE);

   WifiInfo info = wifi.getConnectionInfo();

   macAddress = info.getMacAddress();

   if ( null == macAddress) {

     return "" ;

   }

   macAddress = macAddress.replace( ":" , "" );

   return macAddress;

}

获取当前程序的版本号

public static String getAppVersion(Context context) {

   String version = "" ;

   try {

     version = context.getPackageManager().getPackageInfo(

         context.getPackageName(),  ).versionName;

   } catch (PackageManager.NameNotFoundException e) {

     e.printStackTrace();

   }

   return version;

}

收集设备信息,用于信息统计分析

public static Properties collectDeviceInfo(Context context) {

     Properties mDeviceCrashInfo = new Properties();

     try {

       PackageManager pm = context.getPackageManager();

       PackageInfo pi = pm.getPackageInfo(context.getPackageName(),

           PackageManager.GET_ACTIVITIES);

       if (pi != null ) {

         mDeviceCrashInfo.put(VERSION_NAME,

             pi.versionName == null ? "not set" : pi.versionName);

         mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);

       }

     } catch (PackageManager.NameNotFoundException e) {

       Log.e(TAG, "Error while collect package info" , e);

     }

     Field[] fields = Build. class .getDeclaredFields();

     for (Field field : fields) {

       try {

         field.setAccessible( true );

         mDeviceCrashInfo.put(field.getName(), field.get( null ));

       } catch (Exception e) {

         Log.e(TAG, "Error while collect crash info" , e);

       }

     }

     return mDeviceCrashInfo;

   }

public static String collectDeviceInfoStr(Context context) {

     Properties prop = collectDeviceInfo(context);

     Set deviceInfos = prop.keySet();

     StringBuilder deviceInfoStr = new StringBuilder( "{\n" );

     for (Iterator iter = deviceInfos.iterator(); iter.hasNext();) {

       Object item = iter.next();

       deviceInfoStr.append( "\t\t\t" + item + ":" + prop.get(item)

           + ", \n" );

     }

     deviceInfoStr.append( "}" );

     return deviceInfoStr.toString();

   }

是否有SD卡

public static boolean haveSDCard() {

     return android.os.Environment.getExternalStorageState().equals(

         android.os.Environment.MEDIA_MOUNTED);

   }

动态隐藏软键盘

@TargetApi (Build.VERSION_CODES.CUPCAKE)

   public static void hideSoftInput(Activity activity) {

     View view = activity.getWindow().peekDecorView();

     if (view != null ) {

       InputMethodManager inputmanger = (InputMethodManager) activity

           .getSystemService(Context.INPUT_METHOD_SERVICE);

       inputmanger.hideSoftInputFromWindow(view.getWindowToken(),  );

     }

   }

   @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(),  );

   }

动态显示软键盘

@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,  );

   }

动态显示或者是隐藏软键盘

@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,  );

   }

主动回到Home,后台运行

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

@TargetApi (Build.VERSION_CODES.CUPCAKE)

public static int getStatusBarHeight(Activity activity) {

   Rect frame = new Rect();

   activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

     return frame.top;

   }

获取状态栏高度+标题栏(ActionBar)高度

public static int getTopBarHeight(Activity activity) {

     return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT)

         .getTop();

   }

获取MCC+MNC代码 (SIM卡运营商国家代码和运营商网络代码)

public static String getNetworkOperator(Context context) {

     TelephonyManager telephonyManager = (TelephonyManager) context

         .getSystemService(Context.TELEPHONY_SERVICE);

     return telephonyManager.getNetworkOperator();

   }

返回移动网络运营商的名字

public static String getNetworkOperatorName(Context context) {

     TelephonyManager telephonyManager = (TelephonyManager) context

         .getSystemService(Context.TELEPHONY_SERVICE);

     return telephonyManager.getNetworkOperatorName();

   }

返回移动终端类型

PHONE_TYPE_NONE : 手机制式未知
PHONE_TYPE_GSM : 手机制式为GSM,移动和联通
PHONE_TYPE_CDMA : 手机制式为CDMA,电信
PHONE_TYPE_SIP:
public static int getPhoneType(Context context) {

     TelephonyManager telephonyManager = (TelephonyManager) context

         .getSystemService(Context.TELEPHONY_SERVICE);

     return telephonyManager.getPhoneType();

   }

把一个毫秒数转化成时间字符串

[size=13.3333px]格式为小时/分/秒/毫秒(如:24903600 –> 06小时55分03秒600毫秒)
[size=13.3333px]
/**

    * @param millis

    *            要转化的毫秒数。

    * @param isWhole

    *            是否强制全部显示小时/分/秒/毫秒。

    * @param isFormat

    *            时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。

    * @return 返回时间字符串:小时/分/秒/毫秒的格式(如:24903600 --> 06小时55分03秒600毫秒)。

    */

   public static String millisToString( long millis, boolean isWhole,

       boolean isFormat) {

     String h = "" ;

     String m = "" ;

     String s = "" ;

     String mi = "" ;

     if (isWhole) {

       h = isFormat ? "00小时" : "0小时" ;

       m = isFormat ? "00分" : "0分" ;

       s = isFormat ? "00秒" : "0秒" ;

       mi = isFormat ? "00毫秒" : "0毫秒" ;

     }

     long temp = millis;

     long hper =  *  *  ;

     long mper =  *  ;

     long sper =  ;

     if (temp / hper >  ) {

       if (isFormat) {

         h = temp / hper <  ? "" + temp / hper : temp / hper + "" ;

       } else {

         h = temp / hper + "" ;

       }

       h += "小时" ;

     }

     temp = temp % hper;

     if (temp / mper >  ) {

       if (isFormat) {

         m = temp / mper <  ? "" + temp / mper : temp / mper + "" ;

       } else {

         m = temp / mper + "" ;

       }

       m += "分" ;

     }

     temp = temp % mper;

     if (temp / sper >  ) {

       if (isFormat) {

         s = temp / sper <  ? "" + temp / sper : temp / sper + "" ;

       } else {

         s = temp / sper + "" ;

       }

       s += "秒" ;

     }

     temp = temp % sper;

     mi = temp + "" ;

     if (isFormat) {

       if (temp <  && temp >=  ) {

         mi = "" + temp;

       }

       if (temp <  ) {

         mi = "" + temp;

       }

     }

     mi += "毫秒" ;

     return h + m + s + mi;

   }

格式为小时/分/秒/毫秒(如:24903600 –> 06小时55分03秒)。

/**

    *

    * @param millis

    *            要转化的毫秒数。

    * @param isWhole

    *            是否强制全部显示小时/分/秒/毫秒。

    * @param isFormat

    *            时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。

    * @return 返回时间字符串:小时/分/秒/毫秒的格式(如:24903600 --> 06小时55分03秒)。

    */

   public static String millisToStringMiddle( long millis, boolean isWhole,

       boolean isFormat) {

     return millisToStringMiddle(millis, isWhole, isFormat, "小时" , "分钟" , "秒" );

   }

   public static String millisToStringMiddle( long millis, boolean isWhole,

       boolean isFormat, String hUnit, String mUnit, String sUnit) {

     String h = "" ;

     String m = "" ;

     String s = "" ;

     if (isWhole) {

       h = isFormat ? "" + hUnit : "" + hUnit;

       m = isFormat ? "" + mUnit : "" + mUnit;

       s = isFormat ? "" + sUnit : "" + sUnit;

     }

     long temp = millis;

     long hper =  *  *  ;

     long mper =  *  ;

     long sper =  ;

     if (temp / hper >  ) {

       if (isFormat) {

         h = temp / hper <  ? "" + temp / hper : temp / hper + "" ;

       } else {

         h = temp / hper + "" ;

       }

Android开发常用代码片段的更多相关文章

  1. 36个Android开发常用代码片段

    //36个Android开发常用代码片段 //拨打电话 public static void call(Context context, String phoneNumber) { context.s ...

  2. Android 中常用代码片段

    一:AsyncTask 的使用 (1)activity_main.xml <TextView android:id="@+id/tvInfo" android:layout_ ...

  3. swift开发常用代码片段

    // 绑定事件 cell.privacySwitch.addTarget(self, action: #selector(RSMeSettingPrivacyViewController.switch ...

  4. 转--Android实用的代码片段 常用代码总结

    这篇文章主要介绍了Android实用的代码片段 常用代码总结,需要的朋友可以参考下     1:查看是否有存储卡插入 复制代码 代码如下: String status=Environment.getE ...

  5. 转发—Android开发常用的插件及工具

    作者:蓝之风 出处:http://www.cnblogs.com/vaiyanzi/ Android开发常用的插件及工具 1.GitHub,这个不管是做安卓还是其他,只要是开发就必上的网站,也是天朝没 ...

  6. Android开发常用工具汇总

    Android开发常用工具汇总,本文章不断更新完善 一.数据库小工具Sqlite Developer  SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它的设计目标是嵌入式的, ...

  7. C#常用代码片段备忘

    以下是从visual studio中整理出来的常用代码片段,以作备忘 快捷键: eh 用途: 类中事件实现函数模板 private void MyMethod(object sender, Event ...

  8. Android开发常用开源框架:图片处理

    https://blog.csdn.net/SGQ_CSDN/article/details/79910709 Android开发常用开源框架:图片处理 框架名称 功能描述 Android Unive ...

  9. Vue3.0常用代码片段和开发插件

    Vue3 Snippets for Visual Studio Code Vue3 Snippets源码 Vue3 Snippets下载 This extension adds Vue3 Code S ...

随机推荐

  1. 浅谈ERP系统实施后如何完善企业内部控制制度建设

    ERP与企业内部控制制度,前者提升企业的管理水平,后者为企业发展保驾护航,两项工作都是企业各项工作的重中之重. ERP是企业资源规划Enterprise Resource Planning的缩写.企业 ...

  2. Java 7 中 NIO.2 的使用——第四节 文件和目录

    Files类提供了很多方法用于检查在于你真正实际去操作一个文件或目录.这些方法强烈推荐,也非常有用,也能避免很多异常的发生.例如,一个很好的习惯就是在你试着移动一个文件从一个地方到另一个地方的时候,先 ...

  3. 【bzoj1010】[HNOI2008]玩具装箱toy

    1010: [HNOI2008]玩具装箱toy Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 9281  Solved: 3719[Submit][St ...

  4. 【转载】C++编译出现 error C2664: 不能将参数 2 从“const char [5]”转换为“LPCTSTR”解决办法。

    编译程序的时候出现这样的错误,原因是在新建MFC项目的时候,设置字符集Unicode的属性. 解决方法一: 在VC2010的解决方案管理器窗口内,右击你的项目“项目”,然后选“属性”(最后一项),再点 ...

  5. html5 webApp常用Meta标签

    Html5 webApp常用Meta标签 <meta charset="UTF-8"> <meta name="viewport" conte ...

  6. NET 查找程序集路径(CLR关于Assembly的搜索路径的过程)

    最近在回顾.Net应用程序的执行环境,这里做一个很小的总结,方面以后需要的时候进行查找: CLR必须可以找到正确的Assembly,Net提供了Assembly搜索算法,可以根据.config文件(类 ...

  7. Java中List、Set和Map的区别--转载

    List按对象进入的顺序保存对象,不做排序或编辑操作.Set对每个对象只接受一次,并使用自己内部的排序方法(通常,你只关心某个元素是否属于Set,而不关心它的顺序--否则应该使用List).Map同样 ...

  8. Linux下安装Scim-googlepinyin输入法和设置Sublime Text中文输入

    1.安装git sudo apt-get install git http://www.cnblogs.com/perseus/archive/2012/01/06/2314069.html 2.获取 ...

  9. SOLID 原则

     世纪的前几年里,“ Uncle Bob”Robert Martin 引入了用OOP 开发软件的五条原 则,其目的是设计出更易于维护的高质量系统.无论是设计新应用程序,还是重构现有基 本代码,这些 S ...

  10. PowerDesigner 将CDM、PDM导出为图片

    选中所有对象(Ctrl + A),复制(Ctrl + C),打开系统的“画图”软件,粘贴(Ctrl + V),另存为BMP或者PNG格式即可. 如果是将图片粘贴到Word文档也是可行的.