Android Development: 14 Code Snippets to solve real-world problems

Source: Internet
Author: User

What are some of the problems you will encounter with Android programming? Here for beginners 14 pieces of simple and useful code, save when needed easily a key to get. This includes checking for an SD card, making an activity transparent, setting a handle in the screen element, and so on, and so on, the short code that is often used in practical applications.

1, to see if there is a memory card insert

String status=environment.getexternalstoragestate ();

if (Status.equals (enviroment.media_mounted))

{

Description has SD card insert

}

2, let 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 picture)

3. Set handle in Screen element

Use Activity.findviewbyid to get a handle to the element on the screen that you can use to set or get any values that the object exposes.

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

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);

6, display toast

View Plaincopy

Toast.maketext (This._getapplicationcontext (), R.string._item, Toast.length_short). Show ();

7, Send mail

MIME = "Img/jpg";

Shareintent.setdataandtype (Uri.fromfile (FD), MIME);

Shareintent.putextra (Intent.extra_stream, Uri.fromfile (FD));

Shareintent.putextra (Intent.extra_subject, SUBJECT);

Shareintent.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 context, Intent Intent)

{

String action = Intent.getaction ();

if ("Oms.action.MASTERRESET". Equals (Action))

{

Recoverdefaultconfig ();

}

}

};

9, the definition of contentobserver, monitoring a data table

Private Contentobserver Mdownloadsobserver = new Downloadschangeobserver (Downloads.content_uri);

Private class Downloadschangeobserver extends Contentobserver

{

Public downloadschangeobserver (URI Uri)

{

Super (New Handler ());

}

@Override

public void OnChange (Boolean selfchange) {}

}

10, access to mobile phone UA

Public String getuseragent ()

{

String user_agent = productproperties.get (Productproperties.user_agent_key, NULL);

return user_agent;

}

11, empty the phone cookies

Cookiesyncmanager.createinstance (Getapplicationcontext ());

Cookiemanager.getinstance (). Removeallcookie ();

12, the establishment of 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:

[Java]

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. Get data from specified server via httpclient

Defaulthttpclient httpclient = new Defaulthttpclient ();

HttpGet method = new HttpGet ("/templets/default/index.html");

HttpResponse resp;

Reader reader = null;

try {

Allclientpnames.timeout

Httpparams params = new Basichttpparams ();

Params.setintparameter (Allclientpnames.connection_timeout, 10000);

Httpclient.setparams (params);

Resp = Httpclient.execute (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 ();

}

}

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.