36 typical Android Development classic code Encyclopedia _android

Source: Internet
Author: User

This article brings together 36 typical pieces of code for Android development, including making calls, sending text messages, waking the screen and unlocking them, whether there is a network connection, dynamic display, or hiding a soft keyboard, which I hope will help you.

36 common code Snippets for Android Development//dialing phone public static void call (context context, String PhoneNumber) {context.startactivity (new

  Intent (Intent.action_call, Uri.parse ("Tel:" + phonenumber)); //Jump to the Dial-up interface public static void Calldial (context, String PhoneNumber) {context.startactivity (new Intent (inte Nt.

  Action_dial, Uri.parse ("Tel:" + phonenumber)); //Send SMS public static void Sendsms (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); //Wake up screen and unlock public static void Wakeupandunlock (context context) {Keyguardmanager km= (Keyguardmanager) Context.getsy 

   Stemservice (Context.keyguard_service); 

   Keyguardmanager.keyguardlock KL = Km.newkeyguardlock ("UnLock"); Unlock Kl.disablekeyguard (); 

   Gets the Power Manager Object PowerManager pm= (PowerManager) Context.getsystemservice (Context.power_service); Gets the Powermanager.wakelock object, followed by the parameter | To pass two values at the same time, the last is the logcat tag powermanager.wakelock wl = Pm.newwakelock ( Powermanager.acquire_causes_wakeup | 

   Powermanager.screen_dim_wake_lock, "bright"); 

   Light up the screen wl.acquire (); 

  Release of Wl.release (); //need to add permissions <uses-permission android:name= "Android.permission.WAKE_LOCK"/> <uses-permission android:name= "a Ndroid.permission.DISABLE_KEYGUARD "/>//Determine whether the current app is in the foreground or background state public static Boolean Isapplicationbackground (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;  //need to add permissions <uses-permission android:name= "Android.permission.GET_TASKS"/>//To determine whether the current phone is in a lock screen (sleep) state public static Boolean issleeping {Keyguardmanager kgmgr = (keyguardmanager) context. Getsystemservice (Conte Xt.

   Keyguard_service);

   Boolean issleeping = Kgmgr.inkeyguardrestrictedinputmode ();

  return issleeping;  //Determine if there is currently a network connection 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;  //Determine whether the current WiFi connection state 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;

  }//install 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); //Determine if the current device is a mobile phone public static Boolean Isphone (context context) {Telephonymanager telephony = (Telephonymanager) conte

  XT. Getsystemservice (Context.telephony_service);

  if (telephony.getphonetype () = = Telephonymanager.phone_type_none) {return false;

  else {return true; }//Get current device width high, unit px @SuppressWarnings ("deprecation") public static int getdevicewidth {WindowManager manager = (windowmanager) context. Getsystemservice (Context.window_ser

  VICE);

Return Manager.getdefaultdisplay (). GetWidth (); @SuppressWarnings ("deprecation") public static int Getdeviceheight (context context) {WindowManager manager = (W

  Indowmanager) context. Getsystemservice (Context.window_service);

Return Manager.getdefaultdisplay (). GetHeight (); //Get the IMEI of the current device and need to use the @TargetApi (build.version_codes) with the Isphone () above.

  Cupcake) public static string Getdeviceimei (context context) {string deviceId; if (isphone) {Telephonymanager telephony = (telephonymanager) context. Getsystemservice (Context.teleph

   Ony_service);

  DeviceId = Telephony.getdeviceid ();

  else {deviceId = Settings.Secure.getString (Context.getcontentresolver (), Settings.Secure.ANDROID_ID);

return deviceId;

  //Get the current device's MAC address 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;

  //Get the current program's version number 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; //Collecting equipment information For information statistical analysis public static Properties Collectdeviceinfo (context context) {Properties Mdevicecrashinfo = new P

   Roperties ();

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

   The 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 {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 ();

     }//whether there is SD card public static Boolean Havesdcard () {return android.os.Environment.getExternalStorageState (). Equals (

  Android.os.Environment.MEDIA_MOUNTED); ///Dynamic Hide soft keyboard @TargetApi (build.version_codes.

   Cupcake) public static void Hidesoftinput (activity activity) {View view = Activity.getwindow (). Peekdecorview (); if (view!= null) {Inputmethodmanager Inputmanger = (inputmethodmanager) activity. Getsystemservice (Conte Xt.

    Input_method_service);

   Inputmanger.hidesoftinputfromwindow (View.getwindowtoken (), 0); }} @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); ///Dynamic Display soft keyboard @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); ///dynamic display or hidden soft keyboard @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);

   ///Active return home, background run 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); //Get status bar height/note, to be invoked in onwindowfocuschanged, obtain a height of 0 @TargetApi in OnCreate (build.version_codes.

  Cupcake) public static int getstatusbarheight (activity activity) {Rect frame = new Rect ();

   Activity.getwindow (). Getdecorview (). Getwindowvisibledisplayframe (frame);

  return frame.top; //Get status bar height + title bar (actionbar) Height//(Note that if there is no actionbar, the height of the fetch will be the same as above, only the height of the status bar) public static int Gettopbarheight (

  Activity activity) {return Activity.getwindow (). Findviewbyid (window.id_android_content). GetTop (); //Get MCC+MNC code (SIM card carrier country code and operator Network code)//Only when the user has been registered in the network is valid, CDMA may be invalid (China Mobile: 46000//46002, Unicom: 46001, Chinese Telecom: 46003) Public STA

     Tic String getnetworkoperator {telephonymanager Telephonymanager = (telephonymanager) context

   . Getsystemservice (Context.telephony_service);

  return Telephonymanager.getnetworkoperator (); //Return to the name of the mobile network operator//(for example: China Unicom, Chinese Mobile and China Telecom) The//CDMA may not be valid only if the user is already registered on the network. public static String Getnetworkoperatorname {Telephonymanager Telephonymanager = (telephonymanager) context. Getsystemservice

   (Context.telephony_service);

  return Telephonymanager.getnetworkoperatorname (); }//Back to mobile terminal type phone_type_none:0 Mobile phone format unknown phone_type_gsm:1 mobile phone standard GSM, mobile and unicom phone_type_cdma:2 mobile phone format for CDMA, telecommunications phone_type_sip:3 public static int Getphonetype (C Ontext context) {Telephonymanager Telephonymanager = (telephonymanager) context. Getsystemservice (Context.telep

   Hony_service);

  return Telephonymanager.getphonetype ();

  //Judge the type of network connected by mobile phone (2g,3g,4g)//Unicom 3G for UMTS or HSDPA, mobile and Unicom 2G for GPRS or EGDE, telecom 2G for CDMA, telecom 3G for EVDO 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; 

     public static int Getnetworkclass {Telephonymanager Telephonymanager = (telephonymanager) context

   . Getsystemservice (Context.telephony_service); Switch (Telephonymanager.getnetworktype ()) {case TelephonyManager.NETWORK_TYPE_GPRS:case Telephonymanager.networ K_type_edge:case TelephonyManager.NETWORK_TYPE_CDMA:case TelephonyManager.NETWORK_TYPE_1xRTT:case Telephony

   Manager.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 Telephon

   YManager.NETWORK_TYPE_HSPA:case TelephonyManager.NETWORK_TYPE_EVDO_B:case TELEPHONYMANAGER.NETWORK_TYPE_EHRPD: Case TelephonyManager.NETWORK_TYPE_HSPAP:returnConstants.network_class_3_g;

   Case TelephonyManager.NETWORK_TYPE_LTE:return Constants.network_class_4_g;

   Default:return Constants.network_class_unknown;  }//Determine the network type of the current phone (WiFi or 2,3,4G)//The method that needs to be used is public static int Getnetworkstatus (context context) {int Networktype

   = Constants.network_class_unknown; Connectivitymanager Connectivitymanager = (connectivitymanager) context. Getsystemservice (Context.connectivity_serv

   ICE);

   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; //PX-DP convert public static int dip2px (context context, float Dpvalue) {final float scale = Context.getresourceS (). Getdisplaymetrics (). density;

return (int) (Dpvalue * scale + 0 5f); public static int Px2dip (context context, float Pxvalue) {final float scale = context.getresources (). Getdisplaymetr

  ICS (). Density;

return (int) (Pxvalue/scale + 0 5f); //PX-SP convert public static int PX2SP (context context, float Pxvalue) {final float Fontscale = context.getresources ().

   Getdisplaymetrics (). scaleddensity;

  return (int) (Pxvalue/fontscale + 0 5f); public static int sp2px (context context, float Spvalue) {final float Fontscale = context.getresources (). Getdisplay

   Metrics (). scaleddensity;

  return (int) (Spvalue * fontscale + 0 5f);

  ///Convert a millisecond number into a time string//format of hours/minute/sec/millisecond (such as:24903600–> 06 hours 55 minutes 03 seconds 600 milliseconds)/** * @param Millis * The number of milliseconds to convert.

  * @param iswhole * Force all hours per minute/sec/millisecond.

  * @param Isformat * Time number to be formatted, if true: a few digits ahead of completion; If false: fewer digits ahead of completion.

  * @return return time string: Hours/minute/sec/millisecond format (such as: 24903600--> 06 hours 55 minutes 03 seconds 600 milliseconds). * * public static String millistostring (Long Millis, Boolean iswhole, Boolean Isformat) {String h = "";

   String m = "";

   String s = "";

   String mi = ""; if (iswhole) {h = Isformat?

    "00 hours": "0 Hours"; m = Isformat?

    "00 Points": "0 points"; s = Isformat?

    "00 Seconds": "0 Seconds"; Mi = isformat?

   "00 milliseconds": "0 milliseconds";

   Long temp = Millis;

   Long Hper = 60 * 60 * 1000;

   Long Mper = 60 * 1000;

   Long sper = 1000; if (Temp/hper > 0) {if (Isformat) {h = Temp/hper < 10?

    "0" + Temp/hper:temp/hper + "";

    else {h = temp/hper + "";

   h = "Hour";

   temp = temp% Hper; if (Temp/mper > 0) {if (Isformat) {m = Temp/mper < 10?

    "0" + Temp/mper:temp/mper + "";

    else {m = temp/mper + "";

   } m = = "cent";

   temp = temp% Mper; if (Temp/sper > 0) {if (Isformat) {s = Temp/sper < 10?
"0" + Temp/sper:temp/sper + "";
    else {s = temp/sper + "";

   } s + + "seconds";

   temp = temp% Sper;

   Mi = temp + "";

    if (Isformat) {if (temp < && temp >=) {mi = "0" + temp;

    if (Temp < ten) {mi = "+" + temp;

   } mi = = "MS";

  Return H + m + S + mi;

The format is hour/minute/sec/millisecond (such as:24903600–> 06 hours, 55 minutes, 03 seconds).

  /** * * @param Millis * The number of milliseconds to convert.

  * @param iswhole * Force all hours per minute/sec/millisecond.

  * @param Isformat * Time number to be formatted, if true: a few digits ahead of completion; If false: fewer digits ahead of completion.

  * @return return time string: Hours/minute/sec/millisecond format (such as: 24903600--> 06 hours 55 minutes 03 seconds). */public static String Millistostringmiddle (Long Millis, Boolean iswhole, Boolean Isformat) {return millist

  Ostringmiddle (Millis, Iswhole, Isformat, "hours", "minutes", "seconds"); 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: "0" + hunit; m = Isformat?

    "+" + Munit: "0" + munit; s = Isformat?

   "+" + Sunit: "0" + sunit;

   Long temp = Millis;

   Long Hper = 60 * 60 * 1000;

   Long Mper = 60 * 1000;

   Long sper = 1000; if (Temp/hper > 0) {if (Isformat) {h = Temp/hper < 10?

    "0" + Temp/hper:temp/hper + "";

    else {h = temp/hper + "";

 }

  above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud-dwelling community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.