Android development: 14 code snippets to solve actual problems
What problems will be encountered in Android programming and development? Here we will introduce 14 simple and practical codes for beginners, which can be easily obtained with one click when saved. This includes checking whether there is an SD card, making an Activity transparent, setting a handle in the screen element, and other short code that is frequently used in practical applications.
1. check whether a memory card is 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. With this handle, you can set or obtain any value exposed to this object.
TextView msgTextView = (TextView) findViewById (R. id. msg );
MsgTextView. setText (R. string. push_me );
4. send text messages
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 );
6. Display toast
View plaincopy
Toast. makeText (this. _ getApplicationContext (), R. string. _ item, Toast. LENGTH_SHORT). show ();
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 context, Intent intent)
{
String action = intent. getAction ();
If ("oms. action. MASTERRESET". equals (action ))
{
Recoverdefaconfig config ();
}
}
};
9. Define the ContentObserver and listen to 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. 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 ");
}
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 the specified server through 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.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 ();
}
}