Android Development Common Classic Code Snippets collection _android

Source: Internet
Author: User
Tags get ip

The example of this article summarizes the common code snippets for Android development. Share to everyone for your reference, specific as follows:

1. Picture rotation

Bitmap bitmaporg = Bitmapfactory.decoderesource (This.getcontext (). Getresources (), r.drawable.moon);
Matrix matrix = new Matrix ();
Matrix.postrotate (-90);//rotation angle
Bitmap resizedbitmap = Bitmap.createbitmap (bitmaporg, 0, 0,
          Bitmaporg.getwidth (), Bitmaporg.getheight (), Matrix, true);
Bitmapdrawable BMD = new bitmapdrawable (RESIZEDBITMAP);

2, get mobile phone number

Create phone management
Telephonymanager TM = (Telephonymanager)
//Connect with mobile phone
Activity.getsystemservice ( Context.telephony_service);
Get mobile number
String Phoneid = Tm.getline1number ();
Remember to add
<uses-permission
android:name= "Android.permission.READ_PHONE_STATE" in manifest file/>
//The program cannot be implemented on the simulator and must be connected to the mobile phone

3. Format the string in the String.xml

In Strings.xml.
<string name= "My_text" >thanks for visiting%s. You
are%d!</string>//and in the Java code:
String.Format (getString (R.string.my_text), "Oschina", 33) ;

4, Android Set Full-screen method

A. Set in Java code

/** full screen settings, hidden window all decoration * * * *
requestwindowfeature (window.feature_no_title);
GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_ fullscreen);

B, in the Androidmanifest.xml configuration

<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 the activity for the form of dialog

Configuring the Activity node in Androidmanifest.xml is configured theme 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, to detect whether a intent is effective

public static Boolean isintentavailable (context context, String action) {
  final Packagemanager Packagemanager = Conte Xt.getpackagemanager ();
  Final Intent Intent = new Intent (action);
  list<resolveinfo> list =
      packagemanager.queryintentactivities (Intent,
          Packagemanager.match_ default_only);
  return list.size () > 0;
}

8, Android Phone call

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"); Simulator please use this line
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 browser in Android

Intent viewintent = new
  Intent ("Android.intent.action.VIEW", Uri.parse ("http://vaiyanzi.cnblogs.com"));
StartActivity (viewintent);

11, Android acquisition device unique identification code

String android_id = secure.getstring (GetContext (). Getcontentresolver (), secure.android_id);

12. Get IP address in Android

Public String getlocalipaddress () {
  try {
    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 get the memory card path and usage

/** get the memory card path
/File sdcarddir=environment.getexternalstoragedirectory ();
/** statfs See file system space usage
/statfs statfs=new Statfs (Sdcarddir.getpath ());
size*/
Long blocksize=statfs.getblocksize () of/** block;
/** Total Block Number * *
Long totalblocks=statfs.getblockcount ();
/** already used block number *
/Long availableblocks=statfs.getavailableblocks ();

Add new contacts in 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);

16. Get Process Number

Activitymanager Mactivitymanager = (activitymanager) this.getsystemservice (activity_service);
list<activitymanager.runningappprocessinfo> mrunningprocess = mactivitymanager.getrunningappprocesses ();
int i = 1;
for (Activitymanager.runningappprocessinfo amprocess:mrunningprocess) {
 log.e ("Homer Application", (i++) + "PID =" + Amprocess.pid + "; ProcessName = "+ Amprocess.processname);
}

More interested readers of Android-related content can view this site's topics: "Introduction to Android Development and advanced Tutorials", "Summary of Android Control usage", "Android SMS and phone operation Tips" and "Android Multimedia operating Tips Summary" (audio, video, Recording, etc.) "

I hope this article will help you with the Android program.

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.