Common code snippets for Android development

Source: Internet
Author: User

1. Set the window format to 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 display window Requestwindowfeature (window.feature_no_ TITLE); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_ fullscreen); 4, Get 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, tune 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 Install/uninstall 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. Remove the flatbed navigation getWindow (). Getdecorview (). setsystemuivisibility (8);//Only one special machine is available 13, PowerManager

PowerManager pm = (powermanager) this.getsystemservice (Context.power_service);
WakeLock = Pm.newwakelock (Powermanager.full_wake_lock | Powermanager.acquire_causes_wakeup | Powermanager.on_after_release, "MyLock");

Wakelock.acquire ();

Wakelock.release ();

The flags defined below

Are the parameters to be received in the Newwakelock method, through which you can define how the system's power is displayed. For example:
 *                               &N Bsp                  CPU       screen       Keyboar D
 * partial_wake_lock                  on       &NBSP ; Off             off
 * screen_dim_wake_lock          on &NB Sp       Dim           off
 * screen_bright_wake_lock   on         Bright        off
 * full_wake_lock             & nbsp         on         Bright        bright

These flags are mutually exclusive and can only be defined one at a time.

If you have a partial_wake_lock lock, the CPU will continue to run and fail to enter hibernation, regardless of any timer or even pressing the power button. Unless you let it out.
Other locks, although the CPU is also running, the device will go into hibernation as soon as the user presses the power button.

Normally wakelocks is not actually opened, and when needed, it will start the screen and keyboard with a specific flag. For example, in an application, when it comes to sending a message to a user, it needs to be immediately visible to the user. The screen is lit up at this point. When the Wakelock lock is released, the activity's timer will be reset, which will cause the screen to light up for a longer time.

14, Sharedpreferences

Sharedpreferences sp = getsharedpreferences (Constant.servuce_app, mode_private);

Sp.putstring (key,values);

Editor edit = Sp.edit ();

Edit.commit ();//Modify to remember to submit

15, SQLite

Implement this abstract class Sqliteopenhelper

DBHelper extends Sqliteopenhelper

Implement three methods

DBHelper (context context, String name, cursorfactory factory,int version, Databaseerrorhandler ErrorHandler)

Context//Contexts name//database name Version//Database revision number

OnCreate (Sqlitedatabase db)

The first time you create a DBHelper execution OnCreate method

Onupgrade (sqlitedatabase db, int oldversion, int newversion)

The SQLite version changes when you execute Onupgrade and then execute OnCreate

Common code snippets for Android development

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.