Android Useful Code snippet finishing

Source: Internet
Author: User


Android Code Snippets, the first 1-10 are excerpts from the Internet, to the original author thanks. The back for their own finishing.

1, the format of the window is translucent GetWindow (). SetFormat (pixelformat.translucent); 2. Different ways to update the view on a non-UI thread in android: * Activity.runonuithread (Runnable) * View.post (Runnable) * view.postdelayed (Runnable, Long) * Hanlder3, Full Screen window requestwindowfeature (window.feature_no_title); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_ Fullscreen, WindowManager.LayoutParams.FLAG_FULLSCREEN); 4, get the screen size method A:windowmanager WindowManager = Getwindowmanager ();D Isplay Display = Windowmanager.getdefaultdisplay (); handw[0] = Display.getwidth (); handw[1] = Display.getheight (); Method B:displaymetrics DM = new Displaymetrics (); Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM); handw[0] = DM.WIDTHPIXELS;HANDW[1] = dm.heightpixels;5, browser load URL uri uri = uri.parse ("http://www.google.com"); Intent it = new Intent (Intent.action_view, URI); startactivity (it); 6. Get memory size activitymanager.memoryinfo Outinfo = new Activitymanager.memoryinfo (); Activitymanager.getmemoryinfo (outinfo);//Available memory outinfo.availmem// Whether to get the actual height of scrollview in low memory state outinfo.lowmemory Scrollview.getHeight () scrollview.getmeasuredheight () Scrollview.compute () Scrollview.getlayoutparams (). HEIGHT7, monitoring app installation/ Unload event A.define a class derived from class Broadcastreceiver; B.register broadcast receiver; Mybroadcastreceiver myreceiver = new Mybroadcastreceiver (); intentfilter filter = new Intentfilter (intent.action_ Package_install); filter.addaction (intent.action_package_removed); Filter.addaction (Intent.ACTION_PACKAGE_ADDED) ; Filter.addaction (intent.action_package_changed); filter.addaction (intent.action_package_restarted); Filter.adddatascheme ("package"); This is very important. Otherwise, broadcast can ' t be received.registerreceiver (myreceiver, filter); Notes:the package name is Intent.mdata. Intent.mdata is not available in SDK 1.0, but it can be retrieved by calling Intent.getdatastring (); 8, obtain IP address A.//connect VI A WIFI via Wifiwifimanager Wifimanager = (wifimanager) getsystemservice (Wifi_service); Wifiinfo wifiinfo = Wifimanager.getconnectioninfo (); int ipAddress = Wifiinfo.getipaddress (); B.//coNnect via GPRS via Gprspublic String getlocalipaddress () {try{for (enumeration<networkinterface> en = Networkinterface.getnetworkinterfaces (); En.hasmoreelements ();) {networkinterface intf = en.nextelement (); for (enumeration<inetaddress> enumIpAddr = Intf.getinetaddresses (); Enumipaddr.hasmoreelements ();) {inetaddress inetaddress = enumipaddr.nextelement (); Inetaddress.isloopbackaddress ()) {return inetaddress.gethostaddress (). toString ();}}} catch (SocketException ex) {LOG.E (S.tag, ex.tostring ());} return null;} 9, after the ListView adapter data has changed, but the ListView did not receive notification first, the code that updates the adapter data must be placed in the: Handler.post (Runnable) method; If the source of adapter data if it is the cursor (cursoradapter) can cursor.requery, if it is something else can be forced to call Notifychange, Notifychange will call invalidate 10, Analog HOME key Intent i=new Intent (intent.action_main); i.addcategory (intent.category_home); I.addflags ( Intent.flag_activity_new_task); context.startactivity (i); 11, setting Focus edittext.setfocusable (TRUE); Edittext.requestfocus (); Edittext.setfocusableintouchmode (true);12: Call another app in one app for example: if (utils.isavilible (context, "Com.netschool.main.ui")) {Intent i = new Intent ();    ComponentName cn = New ComponentName ("Com.netschool.main.ui", "com.netschool.main.ui.SplashScreenActivity");    I.setcomponent (CN); StartActivity (i);}    else{uri uri = Uri.parse (context.getstring (r.string.url_zhuanti_download));    Intent it = new Intent (Intent.action_view, URI);    It.setdata (URI); StartActivity (it);} 13:andoroid TextView Display special characters string Course_jianjie = "xxxxxxxxxx";//string with \ r \ n need to be replaced with <br/> string temp =course_jian Jie.replaceall ("\\r\\n", "<br/>");//Use Html to display charsequence Styledtext = html.fromhtml (temp); Set the control Mcoursedesctv.settext (Styledtext) to display, 14: Trigger multiple notification with Notificationmanager, Show only the last problem as long as each different intent corresponds to pass a separate ID on it, the above function is modified as follows (add ID parameter): Private Notification genrenotification (context context, int icon, string tickertext, string title, string content, Intent Intent, int id) {Notification Notification = new Notif Ication (Icon,Tickertext, System.currenttimemillis ()); The problem here is the ID of pendingintent pendintent = pendingintent.getactivity (context, ID, intent, Pendingintent.flag_update_c  urrent);     Notification.setlatesteventinfo (context, title, content, pendintent);     Notification.flags |= Notification.flag_auto_cancel;    return notification; }...mnotificationmanager.notify (Id_1, Genrenotification (Mcontext, Icon_res, NotifyText1, Noti                       FyTitle1, NotifyText1, intent_1, id_1) ... mnotificationmanager.notify (id_2, Genrenotification (Mcontext, Icon_res, NotifyText2, NotifyTitle2, NotifyText2, Intent_2, id_2)); Mnotificationmanager.notify (Id_3, Genr Enotification (Mcontext, Icon_res, NotifyText3, NotifyTitle3, NotifyText3, Intent_3, Id_3)); 15:ADB Command AD b shell/system/bin/screencap-p/sdcard/screenshot.png (save to SDcard) adb pull/sdcard/screenshot.png d:/ Screenshot.png (Save to computer) 16: Jump out of For loop ok:for (int i=0;i<100;i++) {if (i==10) {breakOK; }}17: Loading more than 3 pages with Viewpager sometimes reports the specified child already have a parent. You must call Removeview () the error at the child's parent first: You can simply use Mviewpager.setoffscreenpagelimit (3); Fix Note: Single It's not a panacea, is not the preferred strategy 18:/** * @Description: Adjust the volume size * @author: JRH * @date: 2014-11-13 pm 3:06:46 * @return: void * @param percent */privat e void onvolumeslide (float percent) {if (Mvolume = =-1) {Mvolume = Maudiomanager.getstreamvolume (audiomanager.stream _music); if (Mvolume < 0) {mvolume = 0;}    Moperationbg.setimageresource (R.DRAWABLE.VIDEO_VOLUMN_BG); mvolumebrightnesslayout.setvisibility (View.VISIBLE);    } int index = (int) ((Percent * mmaxvolume) + mvolume); if (Index > Mmaxvolume) {index = mmaxvolume;//maximum volume} else if (Index < 0) {index = 0;//mute}//Change    Sound Maudiomanager.setstreamvolume (audiomanager.stream_music, index, 0);    Change progress bar Viewgroup.layoutparams LP = Moperationpercent.getlayoutparams (); Lp.width = Findviewbyid (r.id.operation_full). Getlayoutparams (). width * Index/mmaxvolume; MOPERATIONPERCENT.SETLAYOUTPARAMS (LP);} 19/** * @Description: Adjust screen brightness * @author: JRH * @date: 2014-11-13 pm 3:17:40 * @return: void * @param percent */private void o Nbrightnessslide (float percent) {if (Mbrightness < 0) {mbrightness = GetWindow (). GetAttributes (). screenbrightness if (mbrightness <= 0.00f) {mbrightness = 0.50f;} else if (Mbrightness < 0.01f) {mbrightness = 0.01f;} Show Moperationbg.setimageresource (R.DRAWABLE.VIDEO_BRIGHTNESS_BG); Mvolumebrightnesslayout.setvisibility (    view.visible);    } windowmanager.layoutparams LPA = GetWindow (). GetAttributes ();    Lpa.screenbrightness = mbrightness + percent; if (Lpa.screenbrightness > 1.0f) {lpa.screenbrightness = 1.0f;//brightest} else if (Lpa.screenbrightness < 0.01f    ) {lpa.screenbrightness = 0.01f;    } GetWindow (). SetAttributes (LPA);    Viewgroup.layoutparams LP = Moperationpercent.getlayoutparams (); Lp.width = (int) (Findviewbyid (r.id.operation_full). GetlayOutparams (). Width * lpa.screenbrightness); MOPERATIONPERCENT.SETLAYOUTPARAMS (LP);} 20:viewpager + fragment layout sometimes reported the following error 11-14 13:52:45.266:e/androidruntime (4561): FATAL exception:main11-14 13:52:45.266 : E/androidruntime (4561): java.lang.nullpointerexception11-14 13:52:45.266:e/androidruntime (4561): at Android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState (fragmentmanager.java:1576) Workaround: Rewrite @Override public void onsaveinstancestate (Bundle outstate) {//TODO auto-generated in the inheritance fragment        Method stub super.onsaveinstancestate (outstate);    Setuservisiblehint (TRUE); }21:service service is not another thread, it is best to process the service separately to process 22: Do not handle time-consuming work in receiver 23: If you want to add a space in the middle of the word, you can use the Space entity number " ;" HTML. Note: A Chinese character is equivalent to two space characters.   The 24:volatile Java keyword ensures that threads can read the write values of other threads, and the Thread.Join () method guarantees that the thread takes precedence over other threads waiting for the Thread.yied () method to make time for other threads to execute how to stop the thread? Do not arbitrarily call the Thread.stop () method, the method is not the correct stop threading method will cause some other problems with the introduction of the flagpole flag: such as setting a Boolean value and so on at the end of the time to clean up resources using code logic to make the thread execution end (the thread line range Part of the code is eitherService execution completed) 25: How to add a line under TEXTVEIW TextView TV = new TextView (); Tv.getpaint (). SetFlags (Paint.underline_text_flag);    26:android more than 4.4 cannot create a folder on an external SD card workaround: @A file Dirfile = new file (Temp.trim ()), if (!dirfile.exists ()) {//is especially important for version 4.4    Getapplicationcontext (). Getexternalfilesdir (NULL);   Dirfile.mkdirs ();} @B file path:/android/data/Package name/27: In: android:targetsdkversion= "18" with the version number of the change interface element, the display way is not the same 28:android get all the memory card address private String[] Getsdcard () {StorageManager sm = (StorageManager) getsystemservice (Context.storage_service); string[] paths = null;try {paths = (string[]) Sm.getclass (). GetMethod ("getvolumepaths", null). Invoke (SM, null);} catch (I Llegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IllegalArgumentException e) {// TODO auto-generated catch Blocke.printstacktrace ();} catch (InvocationTargetException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( Nosuchmethodexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} RetUrn paths;} 29: Baidu Map Problem A: Error java.lang.UnsatisfiedLinkError:Couldn ' t load baidumapsdk_v3_2_0_15 from Loader dalvik.system.pathclassloader[dexpath=/data/app/com.znxh.haohao-1.apk,librarypath=/data/app-lib/ COM.ZNXH.HAOHAO-1]: Findlibrary returned null Workaround: 1: Now libs the Armeabi folder, Then join the. So library file; 2: If the above method does not work: Then build the armeabi-v7a folder under Libs, and then import the corresponding. So library file 3: Be sure to register the service in the Mainfest file when locating: <service android:name= "Com.baidu.location.f" android:enabled= "true" android:process= ": Remote" > </service> 30: Processing image Upload Tool class    /*     * upload Avatar      *       * @param urlstr URL address      *      * @param userid user id   & nbsp *      * @param urlstr images to upload      */    public static Runnable UploadFile (Final Handler Handler, final string urlstring,        final string userid, Final File fiLe)     {    runnable Runnable = new Runnable ()     {         @Override         public void Run ()          {        int res = 0;        string result = Null;&nbs p;       string boundary = Uuid.randomuuid (). toString ();  Boundary identifier randomly generated         string PREFIX = "--", Line_end = "\ r \ n";        string content_type = "Multipart/form-data"; Content Type         try        {             URL url = new URL (urlstring);            HttpURLConnection conn = (httpurlconnection) url.openconnection ();             Conn.setreadtimeout (;  ) &NBsp;        conn.setconnecttimeout ($);             Conn.setdoinput (TRUE); Allow input stream             conn.setdooutput (true); Allow output stream             conn.setusecaches (false); Caching             conn.setrequestmethod ("POST") is not allowed; Request Method             conn.setrequestproperty ("Charset", "UTF-8"); Set encoding             conn.setrequestproperty ("Connection", "keep-alive") ;            conn.setrequestproperty ("Content-type", Content_Type + "; boundary= "+ boundary);            if (file! = null)     & nbsp;       {            /**             Perform uploads when the file is not empty              */             dataoutputstream dos = new DataOutputStream ( Conn.getoutputstream ());            stringbuffer sb = new StringBuffer () ;            sb.append ("--" + boundary + "\ r \ n");             sb.append ("Content-disposition:form-data; Name=\ "userid\" "+" \ r \ n ");            sb.append (" \ r \ n ");            sb.append (userid + "\ r \ n");             sb.append (PREFIX);            sb.append (boundary);             sb.append (line_end);             /**             * Here's the key note: The value in name is the server-side need key only this key can get the corresponding file FileName is the name of the file, with the suffix name              */            sb.append ("Content-disposition:form-data; Name=\ "Photo\"; Filename=\ "" +                file.getname () + "\" "+ Line_ END);            sb.append ("CONTENT-TYPE:IMAGE/PJPEG; charset= "+" UTF-8 "+ line_end);            sb.append (line_end);             dos.write (sb.tostring (). GetBytes ());             inputstream is = new FileInputStream (file);             byte[] bytes = new byte[1024];            int len = 0;&nb sp;  &NBSP;&Nbsp;       while (len = is.read (bytes))! =-1)          & nbsp  {                dos.write (bytes, 0, Len);             }             Is.close ();            dos.write (line_end.getbytes ());            byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes ();  &n Bsp          dos.write (end_data);            dos.flush ();            /**             * Get response code 200 = Success When response is successful, get response flow              */             res = conn.getresponsEcode ();            log.i ("Return code", "Response code:" + res);  & nbsp          log.i ("userid", "" + userid);             if (res = =)             {       & nbsp;        InputStream input = Conn.getinputstream ();                StringBuffer sb1 = new StringBuffer ();                int ss;                 while (ss = Input.read ())! =-1)                  {                sb1.append ((char) SS);                 }                result = sb1.tostring ();                log.i ("return", "Result:" + result);                Message message = Message.obtain ();                 message.what = 666;                 handler.sendmessage (message);             }            else             {                log.i ("Return", " Request Error ");            }            }        }       catch (malformedurlexception e)         {             e.printstacktrace ();        }        catch (IOException e)         {             E.printstacktrace ();        }       }     };    return runnable;   } 


Android Useful Code snippet finishing

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.