Android weather forecast application design (2)

Source: Internet
Author: User
Android weather forecast application design (2) III. Detailed Design

In this article, we refer. In addition, during source code analysis, only schematic and Structured code is selected for analysis. The complete source code of the program can be downloaded at http://download.csdn.net/detail/frankxuanhui/3593051.

(1) multi-thread processing of Weather Information Query

Because the query of weather information involves access to network resources, it may take a long time to access the network in poor network connection conditions. While accessing the network, the main interface of the application is blocked, that is to say, during this period, users cannot interact with the application, resulting in a "false death" status. This is obviously a very bad user experience. To solve this problem, we can create another thread and query the weather forecast in the new thread:

queryButton.setOnClickListener(new OnClickListener(){    public void onClick(View arg0){        new Thread(new Runnable(){            public void run(){                queryWeather();        }).start();    }}

The querybutton button is listened here. When you press this button, a new thread is started and the weather information access method queryweather () is called in the new thread ().

Here, you must pay attention to one problem. Android uses a single-threaded UI, that is, the UI interface can only be refreshed in the main thread. That is to say, when we query the weather information in the queryweather () method, the intuitive idea is to directly refresh the interface in this thread, unfortunately, this method is invalid in Android. We cannot refresh the UI of the main thread in the newly created thread. The solution is to use the handler class:

private class RefreshUIHandler extends Handler {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {             case 1:                                    refreshUI();                               case 2:                                    updateUI();                               default:break;}}}

The preceding method inherits the handler class to create a refreshuihandler for the custom refresh interface, and implements the handlemessage method of the interface method. In this method, the UI update is performed by analyzing the received information. We need to create a refreshuihandler instance in the main thread:

RefreshUIHandler mainHandler = new RefreshUIHandler();

Then, make the following calls where the interface needs to be updated in the new thread:

Message msg = mainHandler.obtainMessage(1);mainHandler.sendMessage(msg);

The code above creates a message object and sends it to mainhandler for processing. It is noted that the parameters in the obtainmessage method correspond to the parameters MSG. What of the handlemessage method in the handler class. In this way, you can refresh the UI in the new thread, and implement multi-thread processing of weather forecast query. (More lightweightAsynctaskThis function has not been studied in this article. I hope to communicate with friends who have done similar functions)

(2) custom pop-up menu Function

On the android real machine, press the menu key to bring up the application menu (the simulator corresponds to the F12 key of the PC keyboard). This function is implemented through oncreateoptionsmenu. There are two ways to create a menu: directly add the menu by using the menu. Add method, or use menuinflater to parse the menu XML document. This article uses the second method:

Public Boolean oncreateoptionsmenu (menu) {menuinflater Inflater = getmenuinflater (); Inflater. inflate (R. menu. operation_menu, menu); // use menuinflater to create a definition in R. menu. return true in operation_menu.xml ;}

Of course, you must first create a folder named menu under the res directory of the project and create the operation_menu.xml document:

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"><item android:id="@+id/send_message" android:icon="@drawable/send_message"android:title="@string/menu_send_message"></item><item android:id="@+id/change_skin" android:icon="@drawable/change_skin"android:title="@string/menu_change_skin"></item><item android:id="@+id/description" android:icon="@drawable/app_description"android:title="@string/menu_description"></item><item android:id="@+id/exit" android:icon="@drawable/exit"android:title="@string/menu_exit"></item></menu>

Finally, implement the corresponding event processing function in the onmenuitemselected method:

public boolean onMenuItemSelected(int featureId, MenuItem item) {switch (item.getItemId()) {case R.id.send_message:                            function1();return true;case R.id.change_skin:                            function2();                            return true;case R.id.exit:                            function3();                            return true;case R.id.description:                            function4();                            return true;default:return false;}}

(3) send SMS

When we query weather forecast information, we sometimes want to directly send a text message to friends and family. This function is easy to implement in Android. This function involves two steps: (1) Getting contact information in the system (2) sending a text message to a specified contact. First, obtain the contact information in the system:

Private Map <string, string> getsystemcontacts () {Map <string, string> contactsmap = new hashmap <string, string> (); cursor cur = getcontentresolver (). query (contacts. people. content_uri, null, null); While (cur. movetonext () {int indexname = cur. getcolumnindex (contacts. lelecolumns. name); // obtain the contact name column index int indexphone = cur. getcolumnindex (contacts. phonescolumns. number); // obtain the index string name = cur. getstring (indexname); string phone = cur. getstring (indexphone); contactsmap. put (name, phone);} cur. close (); Return contactsmap ;}

This method mainly utilizes the contentresolver query method. For details about the query method, refer to the API documentation. This method is similar to SQL operations, the returned cursor class object is a cursor pointing to the result set. You can operate on the cursor to obtain information about all contacts in the system. After obtaining the contact list, you can design an interface to display it on the screen for users to choose from. The next step is to send text messages:

Public void onitemclick (adapterview <?> Arg0, view arg1, int arg2, long arg3) {string phone = phonelist. get (arg2); string name = namelist. get (arg2); smsmanager = smsmanager. getdefault (); // obtain the SMS Manager List <string> dividedmessagelist = smsmanager. dividemessage (Message); // divides the content of the weather forecast text message into multiple messages (if the text message content is greater than 70 characters) for (string message: dividedmessagelist) {smsmanager. sendtextmessage (phone, null, message, null, null); // send SMS }}

The above method is a custom RESPONSE event Method for the contact list listview. When a user selects a contact in the interface, this method will respond. First, get the smsmanager object of the SMS management class, use it to cut the message of the text message content (if the text message length is greater than 70 characters), and then send it to the specified contact.

(4) skin replacement

This feature provides a radiogroup for you to choose from, and changes the background of the main interface to the corresponding image resources based on your selection. However, it should be noted that the background changes disappear after the program exits. The background skin will still display the default image next time you enter the application, instead of the image you have selected, the sharepreferences class should be used to implement the function of saving parameters set by users:

SharedPreferences selectedSkin = getSharedPreferences("skinSelection",Context.MODE_WORLD_READABLE);final SharedPreferences.Editor editor = selectedSkin.edit();skinGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {    public void onCheckedChanged(RadioGroup group, int checkedId) {         if (checkedId == skinBlue.getId()) {                   scrollView.setBackgroundResource(R.drawable.background_blue);            editor.putInt("SELECTED_SKIN",R.drawable.background_blue);        } else if (checkedId == skinGreen.getId()) {                   scrollView.setBackgroundResource(R.drawable.background_green);                   editor.putInt("SELECTED_SKIN",R.drawable.background_green);        }       ...      editor.commit();}

The first sentence of the above Code will generate an XML document named skinselection in the data/<package_name>/shared_prefs directory of the mobile phone or simulator to save the configuration parameters. Then, an editor object is obtained and the putxxx method of the object is used to add information to the XML document. In this way, you can set the UI background by reading this document in the main activity of the application:

scrollView = (ScrollView) findViewById(R.id.scroll_view);SharedPreferences selectedSkin = getSharedPreferences("skinSelection",Context.MODE_PRIVATE);scrollView.setBackgroundResource(selectedSkin.getInt("SELECTED_SKIN",R.drawable.background_blue));

(5) customize the "return" Button Function

The Android system predefines the response event methods for each button. For example, the "return" button can return to the previous interface or exit the application, if we need to customize the RESPONSE event Method of the buttons, We need to override the onkeydown method:

Public Boolean onkeydown (INT keycode, keyevent event) {If (keycode = keyevent. keycode_back) {function ();}/* when you press the menu key, open the menu */If (keycode = keyevent. keycode_menu) {super. openoptionsmenu ();} return true ;}

The above method first checks the key code. If the return key is detected to be pressed, the corresponding processing is performed. Note that because the onkeydown method is rewritten, the predefined menu key of the system will be invalid and the response event of the menu key must be overwritten, as shown in the super in the above Code. openoptionsmenu (). If this line of code is missing, pressing the menu key in the application will be invalid.

(6) automatically enable the soft keyboard after the application is started
After Android starts an application, the focus automatically falls on the first editable interface component from top to bottom and from left to right. Therefore, if this component is an edittext component, when the application is started, the soft keyboard is automatically opened, which affects the user experience. The simplest solution is to open the layout file before defining the first component that generates the focus, define a linearlayout with a size of 0 and set it as the capturing focus:

<LinearLayout android:focusable="true"android:focusableInTouchMode="true" android:layout_width="0px"android:layout_height="0px" />

 

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.