The "Android tool class" Often uses tool classes (methods) Daquan

Source: Internet
Author: User

To collect frequently used tool classes or methods:

1. Get Phone resolution

/** * Get phone Resolution * /public static String Getdisplaymetrix (context context) {if (Constant. screen. screen_width = =0|| Constant. screen. screen_height = =0) {if (context! = null) {int width =0;int height =0;Sharedpreferences Diaplaymetrixinfo = Context. Getsharedpreferences("Display_metrix_info",0);If (context instanceof Activity) {WindowManager WindowManager = (activity) context). Getwindowmanager();Display display = WindowManager. Getdefaultdisplay();Displaymetrics dm = new Displaymetrics ();Display. Getmetrics(DM);width = DM. Widthpixels;Height = DM. Heightpixels;Editor Editor = Diaplaymetrixinfo. Edit();Editor. Putint("width", width);Editor. Putint("Height", height);Editor. Commit();} else {width = Diaplaymetrixinfo. GetInt("width",0);Height = Diaplaymetrixinfo. GetInt("Height",0);} Constant. screen. screen_width = WIDTH;Constant. screen. screen_height = HEIGHT;}} return Constant. screen. screen_width +"x"+ Constant. screen. screen_height;}

2. Turn off the system's soft keyboard

publicclass SoftKeyboardUtil {    /**     * 关闭系统的软键盘     * @param activity     */    publicstaticvoiddismissSoftKeyboard(Activity activity)    {        View view = activity.getWindow().peekDecorView();        ifnull)        {            InputMethodManager inputmanger = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);            0);        }    }}

3. Check if a program is installed

/** * Detects if a program is installed */     Public Static Boolean Isinstalledapp(context context, String PackageName) {Boolean flag =false;Try{Packagemanager pm = Context.getpackagemanager (); List<packageinfo> pkgs = pm.getinstalledpackages (packagemanager.get_uninstalled_packages); for(PackageInfo pkg:pkgs) {//When the name is found and the package name is the same, return                if((Pkg.packagename). Equals (PackageName)) {returnFlag =true; }            }        }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); }returnFlag }

4. Install APK file

/** * Install. apk file * * @param Context */     Public void Install(context context, String fileName) {if(Textutils.isempty (fileName) | | context = =NULL)        {return; }Try{Intent Intent =NewIntent (Intent.action_view);            Intent.setflags (Intent.flag_activity_new_task);            Intent.setaction (Android.content.Intent.ACTION_VIEW); Intent.setdataandtype (Uri.fromfile (NewFile (FileName),"Application/vnd.android.package-archive");        Context.startactivity (Intent); }Catch(Exception e)        {E.printstacktrace (); }    }/** * Install. apk file * * @param Context */     Public void Install(Context context, file file) {Try{Intent Intent =NewIntent (Intent.action_view); Intent.setdataandtype (uri.fromfile (file),"Application/vnd.android.package-archive");        Context.startactivity (Intent); }Catch(Exception e)        {E.printstacktrace (); }    }

5.DP-PX Mutual Conversion

/** * Based on the resolution of the phone from the DP unit to PX (pixels) * * @return return pixel value * *     Public Static int dp2px(Context context,floatDpvalue) {Final floatScale = Context.getresources (). Getdisplaymetrics (). density;return(int) (Dpvalue * scale +0.5f); }/** * According to the resolution of the phone from px (pixels) to the unit to the DP * * @return return the DP value */     Public Static int PX2DP(Context context,floatPxvalue) {Final floatScale = Context.getresources (). Getdisplaymetrics (). density;return(int) (Pxvalue/scale +0.5f); }

6. How to use "%s" in Strings.xml

adding strings to Strings.xml

stringname="text">Hello,%s!</string>

Used in code

textView.setText(String.format(getResources().getString(R.string.text),"Android"));

Output Result: hello,android!

7. Get device unique encoding based on MAC address +deviceid

Private StaticString Devicekey ="";/** * Get device unique code based on MAC address +deviceid * @return  */     Public StaticStringGetdevicekey()    {if("". Equals (Devicekey)) {String macAddress ="";            Wifimanager wifimgr = (Wifimanager) mainapplication.getins (). Getsystemservice (Mainapplication.wifi_service); Wifiinfo info = (NULL= = Wifimgr?NULL: Wifimgr.getconnectioninfo ());if(NULL! = info) {macAddress = Info.getmacaddress (); } Telephonymanager Telephonymanager = (Telephonymanager) mainapplication.getins (). Getsystemservic            E (Mainapplication.telephony_service);            String deviceId = Telephonymanager.getdeviceid (); Devicekey = MD5UTIL.TOMD5 ("Android"+ Constant.appkey + constant.apppwd + macAddress + deviceId); }returnDevicekey; }

8. Get information about your phone and SIM card

/** * Get information about your phone and SIM card * @param context * @return * *     PublicStaticMap<String,String>Getphoneinfo (Context context) {Map<String,String> Map = NewHashMap<String,String>(); Telephonymanager TM=(Telephonymanager) context.Getsystemservice (Context.Telephony_service);StringImei=Tm.Getdeviceid ();StringImsi=Tm.Getsubscriberid ();StringPhonemode=Android.Os.Build.MODEL;StringPhonesdk=Android.Os.Build.VERSION.RELEASE;Map.Put"IMEI", IMEI);Map.Put"IMSI", IMSI);Map.Put"Phonemode", Phonemode+"##"+PHONESDK);Map.Put"Model", Phonemode);Map.Put"SDK", PHONESDK);return Map; }

9. Press the Back button two times to exit the app

 @Override     Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {if(keycode = = Keyevent.keycode_menu) {return false; }//Press two times to exit the app after pressing the back button        if(Apptools.getfirstdata (indexactivity. This))        {if(keycode = = Keyevent.keycode_back) {if(System.currenttimemillis ()-Touchtime > the) {Toast.maketext (indexactivity. This,"Press again to exit the app", Toast.length_short). Show ();                Touchtime = System.currenttimemillis (); }Else{Screenmanager.getscreenmanager (). Popallactivityexceptmain (Indexactivity.class);                Finish (); }            }return true; }Else{return Super. OnKeyDown (KeyCode, event); }    }

The "Android tool class" Often uses tool classes (methods) Daquan

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.