Code snippets frequently used in Android development (1)

Source: Internet
Author: User
Document directory
  • 1. image rotation:
  • 2. Obtain the mobile phone number:
  • 3. format the string in string. xml:
  • 4. How to set full screen for Android:
  • 5. Set activity to dialog:
  • 6. Check whether the current network is connected:
  • 7. Check whether an intent is valid:
  • 8. Android Dialing:
  • 9. Send email in Android:
  • 10. Open a browser in Android:
  • 11. Android obtains the unique identifier of a device:
  • 12. Obtain the IP address in Android:
  • 13. Android obtains the memory card path and usage:
  • 14 Add a new contact to Android:
  • 15. View battery usage:
1. image rotation:
Bitmap bitmaporg = bitmapfactory. decoderesource (this. getcontext (). getresources (), R. drawable. moon); matrix = new matrix (); matrix. postrotate (-90); // Rotation Angle bitmap resizedbitmap = bitmap. createbitmap (bitmaporg, 0, 0, bitmaporg. getwidth (), bitmaporg. getheight (), matrix, true); bitmapdrawable BMI = new bitmapdrawable (resizedbitmap );
2. Obtain the mobile phone number:
// Create telephonymanager TM = (telephonymanager) // create a connection activity with the mobile phone. getsystemservice (context. telephony_service); // obtain the mobile phone number string phoneid = TM. getline1number (); // remember to add <uses-permissionandroid: Name = "android. permission. read_phone_state "/> // The program cannot be implemented on the simulator and must be connected to the mobile phone
3. format the string in string. xml:
// in strings.xml..<string name="my_text">Thanks for visiting %s. You age is %d!</string>          // and in the java code:String.format(getString(R.string.my_text), "oschina", 33);
4. How to set full screen for Android: A. Set it in Java code
/** Full screen setting: Hide all decorations in the window */requestwindowfeature (window. feature_no_title); getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen );
B. Configure in androidmanifest. xml
<activity android:name=".Login.NetEdit"  android:label="@string/label_net_Edit"           android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"><intent-filter><action android:name="android.intent.Net_Edit" /><category android:name="android.intent.category.DEFAULT" /></intent-filter></activity>

5. Set activity to dialog:

Configure theme for activity nodes in androidmanifest. XML as follows:

android:theme="@android:style/Theme.Dialog"
6. Check whether the current network is connected:
ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);   boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();  boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); 

Add permissions in androidmanifest. xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
7. Check whether an intent is valid:
public static boolean isIntentAvailable(Context context, String action) {    final PackageManager packageManager = context.getPackageManager();    final Intent intent = new Intent(action);    List<ResolveInfo> list =            packageManager.queryIntentActivities(intent,                    PackageManager.MATCH_DEFAULT_ONLY);    return list.size() > 0;}
8. Android Dialing:
try {   Intent intent = new Intent(Intent.ACTION_CALL);   intent.setData(Uri.parse("tel:+110"));   startActivity(intent);} catch (Exception e) {   Log.e("SampleApp", "Failed to invoke call", e);}
9. Send email in Android:
Intent I = new intent (intent. action_send); // I. settype ("text/plain"); // use this line for the simulator I. settype ("message/rfc822"); // use this line on the real machine I. putextra (intent. extra_email, new string [] {"test@gmail.com", "test@163.com}); I. putextra (intent. extra_subject, "subject goes here"); I. putextra (intent. extra_text, "body goes here"); startactivity (intent. createchooser (I, "select email application. "));
10. Open a browser in Android:
Intent viewIntent = new     Intent("android.intent.action.VIEW",Uri.parse("http://vaiyanzi.cnblogs.com"));startActivity(viewIntent);
11. Android obtains the unique identifier of a device:
String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
12. Obtain the IP address in Android:
public 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();                if (!inetAddress.isLoopbackAddress()) {                    return inetAddress.getHostAddress().toString();                }            }        }    } catch (SocketException ex) {        Log.e(LOG_TAG, ex.toString());    }    return null;}
13. Android obtains the memory card path and usage:
/** Obtain the memory card path */file sdcarddir = environment. getexternalstoragedirectory ();/** statfs View File System space usage */statfs = new statfs (sdcarddir. getpath ();/** block size */long blocksize = statfs. getblocksize ();/** total number of blocks */long totalblocks = statfs. getblockcount ();/** number of blocks in use */long availableblocks = statfs. getavailableblocks ();
14 Add a new contact to Android:
private Uri insertContact(Context context, String name, String phone) {          ContentValues values = new ContentValues();       values.put(People.NAME, name);       Uri uri = getContentResolver().insert(People.CONTENT_URI, values);       Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);       values.clear();              values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE);       values.put(People.NUMBER, phone);       getContentResolver().insert(numberUri, values);              return uri;}
15. View battery usage:
Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);        startActivity(intentBatteryUsage);
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.