Useful code snippets in android Development

Source: Internet
Author: User

1. Display toast

[Java]
Toast. makeText (this. _ getApplicationContext (), R. string. _ item, Toast. LENGTH_SHORT). show ();
Toast. makeText (this. _ getApplicationContext (), R. string. _ item, Toast. LENGTH_SHORT). show (); [java]
2. View logs
2. Use log to view [java]
Private static final TAG = "MainActivity ";
Log. I (TAG, e. toString ());
Private static final TAG = "MainActivity ";
Log. I (TAG, e. toString (); [java]
3. Set the progress bar
3. Set the progress bar [java]
MProgressDialog = new ProgressDialog (this );
MProgressDialog. setTitle ("prompt"); // set the title
MProgressDialog. setMessage ("The report is being submitted. Please wait..."); // set the body information
MProgressDialog. setProgressStyle (ProgressDialog. STYLE_SPINNER); // set the progress bar style
MProgressDialog. setCancelable (false );
MProgressDialog = new ProgressDialog (this );
MProgressDialog. setTitle ("prompt"); // set the title
MProgressDialog. setMessage ("The report is being submitted. Please wait..."); // set the body information
MProgressDialog. setProgressStyle (ProgressDialog. STYLE_SPINNER); // set the progress bar style
MProgressDialog. setCancelable (false); 4. Take a photo.
[Java]
Intent imageCaptureIntent = new Intent (MediaStore. ACTION_IMAGE_CAPTURE );
StrPath = Environment. getExternalStorageDirectory (). toString () + "/CONSDCGMPIC/"; // folder for storing photos
FileName = new SimpleDateFormat ("yyyyMMddHHmmss"). format (new Date () + ". jpg"; // name the photo
File out = new File (strPath );
If (! Out. exists ()){
Out. mkdirs ();
}
Out = new File (strPath, fileName );
StrPath = strPath + fileName; // absolute path of the photo
ImageCaptureIntent. putExtra (MediaStore. EXTRA_VIDEO_QUALITY, 1 );
StartActivityForResult (imageCaptureIntent, RESULT_CAPTURE_IMAGE );
}
Intent imageCaptureIntent = new Intent (MediaStore. ACTION_IMAGE_CAPTURE );
StrPath = Environment. getExternalStorageDirectory (). toString () + "/CONSDCGMPIC/"; // folder for storing photos
FileName = new SimpleDateFormat ("yyyyMMddHHmmss"). format (new Date () + ". jpg"; // name the photo
File out = new File (strPath );
If (! Out. exists ()){
Out. mkdirs ();
}
Out = new File (strPath, fileName );
StrPath = strPath + fileName; // absolute path of the photo
ImageCaptureIntent. putExtra (MediaStore. EXTRA_VIDEO_QUALITY, 1 );
StartActivityForResult (imageCaptureIntent, RESULT_CAPTURE_IMAGE );
} [Java]
5. Video shooting
5. Video shooting [java]
<Pre class = "java" name = "code"> Intent intent = new Intent (MediaStore. ACTION_VIDEO_CAPTURE );
<Pre class = "java" name = "code"> Intent intent = new Intent (MediaStore. ACTION_VIDEO_CAPTURE); [java]
Intent. putExtra (MediaStore. EXTRA_VIDEO_QUALITY, 0 );
Intent. putExtra (MediaStore. EXTRA_VIDEO_QUALITY, 0); [java]
StartActivityForResult (intent, REQUEST_CODE_TAKE_VIDEO );
StartActivityForResult (intent, REQUEST_CODE_TAKE_VIDEO); [java]
6. Recording
6. Recording [java]
<Pre class = "java" name = "code"> Intent intent = new Intent (Intent. ACTION_GET_CONTENT );
Intent. setType ("audio/amr ");
StartActivityForResult (intent, RESULT_CAPTURE_RECORDER_SOUND );
<Pre class = "java" name = "code"> Intent intent = new Intent (Intent. ACTION_GET_CONTENT );
Intent. setType ("audio/amr ");
StartActivityForResult (intent, RESULT_CAPTURE_RECORDER_SOUND );

 

7. check whether a memory card is inserted.

[Java]
String status = Environment. getExternalStorageState ();
 
If (status. equals (Enviroment. MEDIA_MOUNTED ))
 
{
 
}
String status = Environment. getExternalStorageState ();

If (status. equals (Enviroment. MEDIA_MOUNTED ))

{

}
 

8. Make an Activity transparent

Layout is not set in OnCreate.

[Java]
This. setTheme (R. style. Theme_Transparent );
This. setTheme (R. style. Theme_Transparent );
The above is the definition of Theme_Transparent (note that transparent_bg is a transparent image)

9. Set the handle in the screen element
Use Activity. findViewById to obtain the handle of the elements on the screen. With this handle, you can set or obtain any value exposed to this object.

[Java]
TextView msgTextView = (TextView) findViewById (R. id. msg );
 
MsgTextView. setText (R. string. push_me );
TextView msgTextView = (TextView) findViewById (R. id. msg );

MsgTextView. setText (R. string. push_me );


10. send text messages
[Java]
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 );
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 );


11. Send MMS
[Java]
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 );
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 );


12. Send Mail
[Java]
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 );
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 );


13. Register a BroadcastReceiver
[Java]
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 )){
Recoverdefaconfig config ();
}
}
};
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 )){
Recoverdefaconfig config ();
}
}
};


14. Define the ContentObserver and listen to a data table

[Java]
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 ){
}
15. Obtain <span style = "BACKGROUND-COLOR: transparent"> mobile phone </span> UA.
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 ){
}
15. Obtain <span style = "BACKGROUND-COLOR: transparent"> mobile phone </span> UA.
[Java]
Public String getUserAgent ()
{
String user_agent = ProductProperties. get (ProductProperties. USER_AGENT_KEY, null );
Return user_agent;
}
16. Clear the <span style = "BACKGROUND-COLOR: transparent"> cookie </span>
Public String getUserAgent ()
{
String user_agent = ProductProperties. get (ProductProperties. USER_AGENT_KEY, null );
Return user_agent;
}
16. Clear the <span style = "BACKGROUND-COLOR: transparent"> cookie </span>
[Java]
CookieSyncManager. createInstance (getApplicationContext ());
 
CookieManager. getInstance (). removeAllCookie ();
CookieSyncManager. createInstance (getApplicationContext ());

CookieManager. getInstance (). removeAllCookie ();


17. Establish a GPRS connection
[Java]
// Dial the GPRS link.
 
Private boolean openDataConnection (){
 
// Set up data connection.
 
DataConnection conn = DataConnection. getInstance ();
If (connectMode = 0 ){
Ret = conn. openConnection (mContext, "cmwap ");
} Else {
Ret = conn. openConnection (mContext, "cmnet", "", "");
}
}
// Dial the GPRS link.

Private boolean openDataConnection (){

// Set up data connection.

DataConnection conn = DataConnection. getInstance ();
If (connectMode = 0 ){
Ret = conn. openConnection (mContext, "cmwap ");
} Else {
Ret = conn. openConnection (mContext, "cmnet", "", "");
}
}


18. PreferenceActivity usage
[Java]
Public class Setting extends PreferenceActivity
{
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
AddPreferencesFromResource (R. xml. settings );
}
}
Public class Setting extends PreferenceActivity
{
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
AddPreferencesFromResource (R. xml. settings );
}
}

 

 

Setting. xml:


[Html]
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"/>
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"/>

 

 

 

19. get data from the specified server through HttpClient

[Java]
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 ();
 
}
 
}
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 ();

}

}
 
 

Not complete. To be supplemented...

From the jindegegesun Column
 

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.