Android Programming Utility Code Collection

Source: Internet
Author: User

Convert between 1.android DP and PX public class Densityutil {/** * from dip units to the resolution of the phone as px (pixels) */public static int dip2px (Context conte XT, float Dpvalue) {final float scale = context.getresources (). Getdisplaymetrics (). density; return (int.) (Dpvalue * scale + 0.5f); /** * to the cell phone's resolution from PX (pixels) to the unit to be DP */public static int Px2dip (context context, float Pxvalue) {final float scale = cont Ext.getresources (). Getdisplaymetrics (). density; return (int) (Pxvalue/scale + 0.5f); } }
2.android dialog box style

<style name= "Mydialog" parent= "@android: Theme.dialog" > <item name= "Android:windownotitle" >true</ item> <item name= "Android:windowbackground" > @color/ha</item> </style>
3.android gets the path uri uri by Uri = Data.getdata (); String[] proj = {MediaStore.Images.Media.DATA}; Cursor actualimagecursor = Managedquery (uri,proj,null,null,null); int actual_image_column_index = Actualimagecursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA); Actualimagecursor.movetofirst (); String Img_path = actualimagecursor.getstring (Actual_image_column_index); File File = new file (Img_path);
4.android get real path based on URI public static String Getrealfilepath (final context context, final Uri uri) {if (null = = URI) return null; final Strin G scheme = Uri.getscheme (); String data = null; if (scheme = = null) data = Uri.getpath (); else if (ContentResolver.SCHEME_FILE.equals (SCHEME)) {data = Uri.getpath ();} else if (Contentresolver.scheme_conten T.equals (Scheme)) {cursor cursor = context.getcontentresolver (). Query (URI, new string[] {imagecolumns.data}, NULL, NULL, NULL); if (null! = cursor) {if (Cursor.movetofirst ()) {int index = Cursor.getcolumnindex (Imagecolumns.data), if (Index & Gt -1) {data = cursor.getstring (index);}} Cursor.close (); }} return data; }
5.android Restore SMS Contentvalues values = new Contentvalues (); Values.put ("Address", "123456789"); Values.put ("Body", "haha"); Values.put ("date", "135123000000"); Getcontentresolver (). Insert (Uri.parse ("content://sms/sent"), values);
6.android Toggle < activity android:name= "myactivity" android:configchanges= "Orientation|keyboardhidden" > public void onconfigurationchanged (Configuration newconfig) {super.onconfigurationchanged (newconfig); This.getresources (). GetConfiguration (). Orientation = = Configuration.orientation_landscape) {//Add horizontal screen to process the code}else if ( This.getresources (). GetConfiguration (). Orientation = = configuration.orientation_portrait) {//Add code to be processed by vertical screen}}
7.android get MAC address 1, <uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/> 2, Private String getlocalmacaddress () {Wifimanager WiFi = (wifimanager) getsystemservice (Context.wifi_service); Wifiinfo info = Wifi.getconnectioninfo (); return info.getmacaddress (); 8.android get SD card status/** get memory card path */File sdcarddir=environment.getexternalstoragedirectory (); /** StatFs See File system space Usage */StatFs statfs=new StatFs (Sdcarddir.getpath ()); /** Block of size*/Long blocksize=statfs.getblocksize (); /** Total Block number */Long totalblocks=statfs.getblockcount (); /** number of blocks already used */Long availableblocks=statfs.getavailableblocks ();
9.android get title bar status bar height Android get status bar and title bar height 1.Android Get status bar height: Decorview is the topmost view in the window and can be obtained from the window to Decorview, Then Decorview has a getwindowvisibledisplayframe method to get to the area that the program displays, including the title bar, but not the status bar. So we can figure out the height of the status bar. Rect frame = new Rect (); GetWindow (). Getdecorview (). Getwindowvisibledisplayframe (frame); int statusbarheight = Frame.top; 2. Get the title bar height: GetWindow (). Findviewbyid (Window.id_android_content) This method gets the view that the program does not include the title bar section, and then you can know the height of the title bar. int contenttop = GetWindow (). Findviewbyid (window.id_android_content). GetTop (); Statusbarheight is the height of the status bar above, int titlebarheight = Contenttop-statusbarheight Example code: Package COM.CN.LHQ; Import android.app.Activity; Import Android.graphics.Rect; Import Android.os.Bundle; Import Android.util.Log; Import Android.view.Window; Import Android.widget.ImageView; public class Main extends Activity {ImageView IV; @Override public void OnCreate (Bundle savedinstancestate) {Super.oncre Ate (savedinstancestate); Setcontentview (R.layout.main); IV = (ImageView) This.findviewbyid (R.ID.IMAGEVIEW01); Iv.post (nEW Runnable () {public void run () {viewinited ();}}); LOG.V ("Test", "= = OK = ="); } private void Viewinited () {rect rect = new Rect (); window window = GetWindow (); Iv.getwindowvisibledisplayframe (rect); int statusbarheight = Rect.top; int contentviewtop = Window.findviewbyid (window.id_android_content). GetTop (); int titlebarheight = Contentviewtop-statusbarheight; Test result: OK after more than 100 ms Run LOG.V ("Test", "=-init-= statusbarheight=" + statusbarheight + "contentviewtop=" + contentviewto p + "titlebarheight=" + titlebarheight); }} <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " > <imageview android:id= "@+id/imageview01" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content "/> </LinearLayout>
10.android get various form heights//Get Window Properties Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM); The width of the window int screenwidth = dm.widthpixels; window height int screenheight = dm.heightpixels; TextView = (TextView) Findviewbyid (R.ID.TEXTVIEW01); Textview.settext ("screen width:" + screenwidth + "\ n Screen Height:" + screenheight); Second, get the status bar height Decorview is the topmost view in the window, you can get the Decorview from the window, Then Decorview has a getwindowvisibledisplayframe method to get to the area that the program displays, including the title bar, but not the status bar. So we can figure out the height of the status bar. View Plain rect frame = new Rect (); GetWindow (). Getdecorview (). Getwindowvisibledisplayframe (frame); int statusbarheight = Frame.top; Third, get the title bar height GetWindow (). Findviewbyid (Window.id_android_content) This method gets to the view that the program does not include the title bar of the section, and then you can know the height of the title bar. View plain int contenttop = GetWindow (). Findviewbyid (window.id_android_content). GetTop (); Statusbarheight is the height of the status bar that was asked above int titlebarheight = contenttop-statusbarheight11.android Disable Home keyboard issue Android Home Key System is responsible for monitoring, after capturing the system automatically processing. Sometimes, the processing of the system often does not follow our intention, want to handle the event after clicking Home, then what to do? Solve the problem first prohibit the home button, and then in the onkeydown Processing key values, click the Home button when the program closed, or with you xxoo. @Override public boolean onKeyDown (int keycode, keyevent event) {//TODO auto-generated Method stub if (Keyevent.keycode_ho Me==keycode) android.os.Process.killProcess (Android.os.Process.myPid ()); Return Super.onkeydown (KeyCode, event); } @Override public void Onattachedtowindow () {//TODO auto-generated Method Stub This.getwindow (). SetType (WindowManager. Layoutparams.type_keyguard); Super.onattachedtowindow (); } Plus permissions prohibit home key <uses-permission android:name= "Android.permission.DISABLE_KEYGUARD" ></uses-permission>
12.android boot public class Startupreceiver extends Broadcastreceiver {@Override public void onreceive (context context, I Ntent Intent) {Intent startupintent = new Intent (Context,strongtracks.class); Startupintent.addflags (intent.flag_ Activity_new_task); Context.startactivity (startupintent); }} 2) <receiver android:name= ". Startupreceiver "> <intent-filter> <!--call--<action android:name=" When system boot is complete " Android.intent.action.BOOT_COMPLETED "> </action> </intent-filter> </receiver> 13.android Control dialog Box Location window =dialog.getwindow ();//Get dialog box. Windowmanager.layoutparams wl = Window.getattributes (); Wl.x = x;//These two sentences set the position of the dialog box. 0 for Middle Wl.y =y; Wl.width =w; Wl.height =h; Wl.alpha =0.6f;//This sentence sets the transparency of the dialog box 14.android reposition the dialog position Window Mwindow = Dialog.getwindow (); Windowmanager.layoutparams LP = Mwindow.getattributes (); lp.x = 10; New position x Coordinate lp.y =-100; New position y coordinate dialog.onwindowattributeschanged (LP) 15.android determine network status <uses-permission android:name= " Android.permission.aCcess_network_state "/> Private Boolean Getnetworkstatus () {Boolean Netsataus = false; Connectivitymanager Cwjmanager = (connectivitymanager) getsystemservice (Context.connectivity_service); Cwjmanager.getactivenetworkinfo (); if (cwjmanager.getactivenetworkinfo () = null) {Netsataus = Cwjmanager.getactivenetworkinfo (). isavailable ();} if (! Netsataus) {Builder b = new Alertdialog.builder (this). Settitle ("No Network Available"). Setmessage ("Do you want to set up the network?"). "); B.setpositivebutton ("Yes", new Dialoginterface.onclicklistener () {public void OnClick (dialoginterface dialog, int Whichbutton) {Intent mintent = new Intent ("/"); ComponentName comp = new ComponentName ("Com.android.settings", "com.android.settings.WirelessSettings"); Mintent.setcomponent (comp); Mintent.setaction ("Android.intent.action.VIEW"); Startactivityforresult (mintent,0); }}). Setneutralbutton ("No", new Dialoginterface.onclicklistener () {public void OnClick (dialoginterface dialog, int Whichbutton) {dialog.cancel ();}}). Show (); } return NetSataus; } 16.android Set Apncontentvalues values = new Contentvalues (); Values.put (NAME, "CMCC cmwap"); Values.put (APN, "Cmwap"); Values.put (PROXY, "10.0.0.172"); Values.put (PORT, "80"); Values.put (Mmsproxy, ""); Values.put (Mmsport, ""); Values.put (USER, ""); Values.put (SERVER, ""); Values.put (PASSWORD, ""); Values.put (MMSC, ""); Values.put (TYPE, ""); Values.put (MCC, "460"); Values.put (MNC, "00"); Values.put (NUMERIC, "46000"); Reuri = Getcontentresolver (). Insert (Uri.parse ("Content://telephony/carriers"), values); Preferred access point "CONTENT://TELEPHONY/CARRIERS/PREFERAPN" 17.android adjust screen brightness public void setbrightness (Int. level) { Contentresolver CR = Getcontentresolver (); Settings.System.putInt (CR, "screen_brightness", level); window window = GetWindow (); Layoutparams attributes = Window.getattributes (); float flevel = level; attributes.screenbrightness = flevel/255; GetWindow (). SetAttributes (attributes); }
18.android RestartFirst, root permission, which is required second, runtime.getruntime (). EXEC ("su-c reboot"); Third, the simulator can not run out, must be true machine IV, the runtime will prompt you whether to join the list, agree on the good
19.android resource uriandroid.resource://com.packagename/raw/xxxx20.android Hidden soft keyboard Setcontentview (R.layout.activity_main ); GetWindow (). Setsoftinputmode (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
21.android hides and displays the soft keyboard and does not automatically eject the keyboard Method 1,//Hide soft keyboard ((Inputmethodmanager) Getsystemservice (Input_method_service)). Hidesoftinputfromwindow (WidgetSearchActivity.this.getCurrentFocus (). Getwindowtoken (), Inputmethodmanager.hide_ Not_always); 2,//Display the soft keyboard, the control ID can be Edittext,textview ((Inputmethodmanager) Getsystemservice (Input_method_service)). Showsoftinput ( Control ID, 0); 22.BitMap, drawable, InputStream and byte[] Mutual transfer (1) BitMap to inputstream:bytearrayoutputstream BAOs = new Bytearrayoutputstream (); Bm.compress (Bitmap.CompressFormat.PNG, BAOs); InputStream ISBM = new Bytearrayinputstream (BAOs. Tobytearray ()); (2) BitMap to byte[]: BitMap DefaultIcon = Bitmapfactory.decodestream (in); Bytearrayoutputstream stream = new Bytearrayoutputstream (); Defaulticon.compress (Bitmap.CompressFormat.JPEG, N, Stream); byte[] BitmapData = Stream.tobytearray (); (3) drawable to byte[]: drawable D; The drawable (Captain Obvious, to the rescue!!!) Bitmap Bitmap = ((bitmapdrawable) d). Getbitmap (); Bytearrayoutputstream stream = new BytEarrayoutputstream (); Defaulticon.compress (Bitmap.CompressFormat.JPEG, Bitmap); byte[] BitmapData = Stream.tobytearray (); (4) byte[] to Bitmap:bitmap Bitmap =bitmapfactory.decodebytearray (byte[], 0,byte[].length); 23. Send Instruction out = Process.getoutputstream (); Out.write ("Am start-a android.intent.action.view-n com.android.browser/com.android.browser.browseractivity\n"). GetBytes ()); Out.flush (); InputStream in = Process.getinputstream (); BufferedReader re = new BufferedReader (new InputStreamReader (in)); String line = null; while (line = Re.readline ()) = null) {LOG.D ("Conio", "[result]" +line);
24.Android determine if GPS is on and force the user to open gpshttp://blog.csdn.net/android_ls/article/details/8605931 intro: When our app provides location services to users, Often want to provide users with a precise point of location services, which requires the user to cooperate. We must first detect the user's mobile phone's GPS is currently open, if not open, pop-up dialog box prompt. If users do not cooperate with us, we can only use the base station positioning method. If our application must be opened by the user to use the GPS, then the rogue point of action is to force users to open the GPS.
Clarifying Concepts:
Location Services GPS: A global satellite positioning system, using a network of 24 satellites to triangulate the position of the receiver and provide latitude and longitude coordinates. While GPS provides excellent positional accuracy, the location of the positioning needs to be seen where a satellite or track is visible.
Location Services AGPS: Auxiliary global satellite Positioning System (English: Assisted Global Positioning System, abbreviation: AGPS) is a mode of operation of GPs. It can use the mobile phone base station information, with the traditional GPS satellite, so that positioning faster. In Chinese, it should be a network-aided GPS positioning system. Popularly said that aGPS is in the past through the satellite to accept the location of the signal and the mobile operation of the GSM or CDMA network station positioning information, on the one hand from the mobile phone with aGPS to obtain from the satellite positioning information, but also rely on the mobile phone through the GPRS network of China Mobile download Auxiliary positioning information, The two combine to complete the positioning. With the traditional GPS (Globalpositioningsystem Global Positioning System) first positioning to 2, 3 minutes compared to the aGPS first time to locate the fastest only a few seconds, while the AGPS also completely solve the general GPS equipment in the room can not obtain location information defects.
First, the detection of the user's mobile phone GPS is currently open, the code is as follows:
[Java] View plaincopy
/**
* Determine if GPS is turned on, GPS or aGPS to open a
* @param context
* @return True indicates open
*/
public static Final Boolean IsOPen (final context context) {
Locationmanager Locationmanager
= (Locationmanager) context.getsystemservice (Context.location_service);
GPS satellite positioning, positioning level can be accurate to the street (through 24 satellite positioning, in the outdoor and open location accurate, fast)
Boolean GPS = locationmanager.isproviderenabled (Locationmanager.gps_provider);
A location determined by the WLAN or mobile network (3G/2G), also known as AGPS, assists with GPS positioning. Mainly used in indoor or in the shelter (complex or dense deep forest, etc.) dense place positioning)
Boolean network = locationmanager.isproviderenabled (Locationmanager.network_provider);
if (GPS | | network) {
return true;
}

return false;
}
Second, the force to help users open the GPS, the code is as follows:
[Java] View plaincopy
/**
* Force the user to open the GPS
* @param context
*/
public static final void Opengps (context context) {
Intent gpsintent = new Intent ();
Gpsintent.setclassname ("Com.android.settings",
"Com.android.settings.widget.SettingsAppWidgetProvider");
Gpsintent.addcategory ("Android.intent.category.ALTERNATIVE");
Gpsintent.setdata (Uri.parse ("Custom:3"));
try {

Pendingintent.getbroadcast (context, 0, gpsintent, 0). Send ();

} catch (Canceledexception e) {
E.printstacktrace ();
}
}
Third, in the Androidmanifest.xml file need to add the permissions:
[HTML] View plaincopy
<uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name= "Android.permission.INTERNET"/>

Android Programming Utility Code Collection

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.