Useful Android code snippets

Source: Internet
Author: User
Tags transparent image

1: Check whether there is a memory card inserted

String status = environment. getexternalstoragestate ();

If (status. Equals (enviroment. media_mounted ))

{

SD card insertion

}

 

2: Make an activity transparent

 

Layout is not set in oncreate.

 

This. settheme (R. style. theme_transparent );

 

The following is the definition of theme_transparent (note that transparent_bg is a transparent image)

 

3: Set the handle in the screen element

Use activity. findviewbyid to obtain the handle of the elements on the screen.

Set or obtain any exposed value of this object.

Textview msgtextview = (textview) findviewbyid (R. Id. msg );

Msgtextview. settext (R. String. push_me );

 

4: send SMS

 

String body = "this is MMS Demo ";

 

Intent mmsintent = new intent (intent. action_sendto,

Uri. fromparts ("smsto", number, null ));

 

Mmsintent. putextra (messaging. key_action_sendto_message_body, body );

 

Mmsintent. putextra (messaging. key_action_sendto_compose_mode, true );

 

Mmsintent. putextra (messaging. key_action_sendto_exit_on_sent, true );

Startactivity (mmsintent );

 

5. Send MMS messages

 

Stringbuilder sb = new stringbuilder ();

 

SB. append ("file ://");

 

SB. append (FD. getabsolutefile ());

 

Intent intent = new intent (intent. action_sendto,

Uri. fromparts ("mmsto", number, null ));

// Below extra datas are all optional.

 

Intent. putextra (messaging. key_action_sendto_message_subject, subject );

 

Intent. putextra (messaging. key_action_sendto_message_body, body );

Intent. putextra (messaging. key_action_sendto_content_uri,

SB. tostring ());

 

Intent. putextra (messaging. key_action_sendto_compose_mode,

Composemode );

Intent. putextra (messaging. key_action_sendto_exit_on_sent,

Exitonsent );

 

Startactivity (intent );

 

7: Send mail

 

Mime = "img/jpg ";

Using intent. setdataandtype (URI. fromfile (FD), mime );

Extends intent. putextra (intent. extra_stream, Uri. fromfile (FD ));

Specify intent. putextra (intent. extra_subject, subject );

 

Extends intent. putextra (intent. extra_text, body );

 

8: register a broadcastreceiver

 

Registerreceiver (mmasterresetreciever, new

Intentfilter ("OMS. Action. masterreset "));

 

Private broadcastreceiver mmasterresetreciever = new broadcastreceiver (){

 

Public void onreceive (context, intent ){

String action = intent. getaction ();

If ("OMS. Action. masterreset". Equals (Action )){

 

Recoverdefaconfig config ();

}

}

 

};

 

9: Define contentobserver to listen to a data table

 

Private contentobserver mdownloadsobserver = new

Downloadschangeobserver (downloads. content_uri );

 

Private class downloadschangeobserver extends contentobserver {

Public downloadschangeobserver (URI ){

Super (new handler ());

 

}

 

@ Override

Public void onchange (Boolean selfchange ){}

}

 

 

10: Get the UA

 

Public String getuseragent ()

{

String user_agent =

Productproperties. Get (productproperties. user_agent_key, null );

Return user_agent;

}

 

11: Clear cookies on mobile phones

 

Cookiesyncmanager. createinstance (getapplicationcontext ());

Cookiemanager. getinstance (). removeallcookie ();

 

12. Establish a GPRS connection

 

// Dial the GPRS link.

Private Boolean opendataconnection (){

// Set up data connection.

Dataconnection conn = dataconnection. getinstance ();

 

If (connectmode = 0 ){

Ret = conn. openconnection (mcontext, "cmwap", "cmwap ",

"Cmwap ");

} Else {

Ret = conn. openconnection (mcontext, "cmnet", "", "");

}

 

}

 

13: preferenceactivity usage

 

Public class setting extends preferenceactivity

 

{

 

Public void oncreate (bundle savedinstancestate ){

Super. oncreate (savedinstancestate );

Addpreferencesfromresource (R. xml. settings );

}

 

}

 

Setting. xml:

 

Android: Key = "seting2 ″

Android: Title = "@ string/seting2 ″

Android: Summary = "@ string/seting2"/>

 

Android: Key = "seting1 ″

Android: Title = "@ string/seting1 ″

Android: summaryoff = "@ string/seting1summaryoff"

Android: summaryon = "@ stringseting1summaryoff"/>

 

14. Use httpclient to obtain data from a specified server

 

Defaulthttpclient httpclient = new defaulthttpclient ();

Httpget method = new

Httpget ("http://www.baidu.com/1.html ");

Httpresponse resp;

Reader reader = NULL;

Try {

// Allclientpnames. Timeout

Httpparams Params = new basichttpparams ();

 

Params. setintparameter (allclientpnames. connection_timeout, 10000 );

 

Httpclient. setparams (Params );

Resp = httpclient.exe cute (method );

Int status = resp. getstatusline (). getstatuscode ();

 

If (status! = Httpstatus. SC _ OK) return false;

 

// Httpstatus. SC _ OK;

Return true;

} Catch (clientprotocolexception e ){

// Todo auto-generated Catch Block

E. printstacktrace ();

} Catch (ioexception e ){

// Todo auto-generated Catch Block

E. printstacktrace ();

} Finally {

If (reader! = NULL) Try {

Reader. Close ();

} Catch (ioexception e ){

// Todo auto-generated Catch Block

E. printstacktrace ();

}

}

 

15: Display toast

Toast. maketext (this. _ getapplicationcontext (), R. String. _ item,

Toast. length_short). Show ();

 

16: Start another activity in the current activity

Startactivity (new intent (this, target activity. Class ));

17: Query controls from the current contentview

(Button) findviewbyid (R. Id. btnabout)

R. Id. btnabout indicates the Control ID.

18: Get screen width and height

Displaymetrics dm = new displaymetrics ();

// Obtain window properties

Getwindowmanager (). getdefaultdisplay (). getmetrics (DM );

Int screenwidth = DM. widthpixels; // 320

Int screenheight = DM. heightpixels; // 480

19: No title bar, full screen

// No title bar

Requestwindowfeature (window. feature_no_title );

// Full screen mode

Getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen,

Windowmanager. layoutparams. flag_fullscreen );

 

Note that it is called before setcontentview (); otherwise, it is invalid.

20 register an activity

All activities used must be registered in androidmanifest. xml. Otherwise, a null pointer is reported.

Error.

For example, note the package name + class name.

 

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.