Android mobile guard-Parse json and message mechanisms to send different types of messages, androidjson

Source: Internet
Author: User
Tags error status code

Android mobile guard-Parse json and message mechanisms to send different types of messages, androidjson

URL: http://www.cnblogs.com/wuyudong/p/5900800.html.

1. parse json data

Json parsing code is simple

JSONObject jsonObject = new JSONObject (json); // debug, solve the problem String versionName = jsonObject. getString ("versionName"); mVersionDes = jsonObject. getString ("versionDes"); String versionCode = jsonObject. getString ("versionCode"); mDownloadUrl = jsonObject. getString ("downloadUrl"); // Log print Log. I (tag, versionName); Log. I (tag, mVersionDes); Log. I (tag, versionCode); Log. I (tag, mDownloadUrl );
2. Use the message mechanism to send different types of messages

Obtain the app version number after obtaining the server-side json data, and compare it with the client version number.

// Compare the version (server version> local version, prompting the user to update) if (mLocalVersionCode <Integer. parseInt (versionCode) {// prompt for user updates. the pop-up dialog box (UI) and message mechanism msg are displayed. what = UPDATE_VERSION;} else {// enter the main application interface msg. what = ENTER_HOME ;}

You can use the message mechanism of android to send different types of messages. For details, refer to introduction to Android message mechanism.

Create Handler first

Private Handler mHandler = new Handler () {// public void handleMessage (android. OS. message msg) {switch (msg. what) {case UPDATE_VERSION: // the pop-up dialog box prompts the user to update // showUpdateDialog (); break; case ENTER_HOME: // enter the main interface of the application. enterHome (); break; case URL_ERROR: // ToastUtil. show (getApplicationContext (), "url exception"); enterHome (); break; case IO_ERROR: // ToastUtil. show (getApplicationContext (), "Read exception"); enterHome (); break; case JSON_ERROR: // ToastUtil. show (getApplicationContext (), "json parsing exception"); enterHome (); break; default: break ;}};};

You can define some status codes and error codes when exceptions occur:

/*** Update the status code of the new version */protected static final int UPDATE_VERSION = 100;/*** enter the status code of the main interface of the application */protected static final int ENTER_HOME = 101; /*** url address error Status Code */protected static final int URL_ERROR = 102; // The following are other error status codes protected static final int IO_ERROR = 103; protected static final int maid = 104;

Then implement the enterHome () function. function: Jump to the main interface

/*** Enter the main interface of the application */protected void enterHome () {Intent intent = new Intent (this, HomeActivity. class); startActivity (intent); // after a new interface is enabled, close the navigation interface (the navigation interface is visible only once) finish ();}

So by the way, create a HomeActivity. java

public class HomeActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_home);    }}

Of course, there is also an activity_home.xml file, add a little code, first see the effect, and then modify

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView        android:text="HOMEACTIVITY"        android:textSize="20sp"        android:textColor="#000"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>

After running the project, it is found that when no version update is available, the splash interface will stay for a short time, so you can specify the sleep time. When the request network duration exceeds 4 seconds, no processing will be performed, if the request network duration is less than 4 seconds, it is forced to sleep for 4 seconds. In this way, the splash interface will stay for a while and then jump to the HomeActivity interface.

// Specify the sleep time. If the request network duration is greater than 4 seconds, no processing is performed. // The request network duration is less than 4 seconds. Force the request to sleep for 4 seconds. long endTime = System. currentTimeMillis (); if (endTime-startTime <4000) {try {Thread. sleep (4000-(endTime-startTime);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}} mHandler. sendMessage (msg );

The complete code is as follows:

Package com. wuyudong. mobilesafe. activity; import java. io. IOException; import java. io. inputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import org. json. JSONException; import org. json. JSONObject; import com. wuyudong. mobilesafe. r; import com. wuyudong. mobilesafe. utils. streamUtil; import android. OS. bundle; import android. OS. handler; import android. OS. message; Import android. app. activity; import android. content. intent; import android. content. pm. packageInfo; import android. content. pm. packageManager; import android. util. log; import android. widget. textView;/*** @ author wuyudong ***/public class SplashActivity extends Activity {protected static final String tag = "SplashActivity "; /*** update the status code of the new version */protected static final int UPDATE_VERSION = 100;/*** enter the application Status Code */protected static final int ENTER_HOME = 101;/*** url address error Status Code */protected static final int URL_ERROR = 102; // The following are other error status codes protected static final int IO_ERROR = 103; protected static final int JSON_ERROR = 104; private TextView TV _version_name; private int mLocalVersionCode; private String mVersionDes; private String mDownloadUrl; private Handler mHandler = new Handler () {// public vo Id handleMessage (android. OS. message msg) {switch (msg. what) {case UPDATE_VERSION: // the pop-up dialog box prompts the user to update // showUpdateDialog (); break; case ENTER_HOME: // enter the main interface of the application. enterHome (); break; case URL_ERROR: // ToastUtil. show (getApplicationContext (), "url exception"); enterHome (); break; case IO_ERROR: // ToastUtil. show (getApplicationContext (), "Read exception"); enterHome (); break; case JSON_ERROR: // ToastUtil. show (ge TApplicationContext (), "json parsing exception"); enterHome (); break; default: break ;};};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // remove the tittle of the current actinity // requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. activity_splash); // initialize the UI initUI (); // initialize the data initData ();}/*** enter the main interface of the application */protected void enterHome () {Intent intent = New Intent (this, HomeActivity. class); startActivity (intent); // after a new interface is enabled, close the navigation interface (the navigation interface is visible only once) finish ();} /*** method for obtaining data */private void initData () {// 1. application version name TV _version_name.setText ("version name:" + getVersionName (); // checks whether (the local version number is compared with the server version number) is updated. If yes, prompt the user to download // 2. get the local version number mLocalVersionCode = getVersionCode (); // 3, get the server version number (client sends a request, the service returns a response, (json, xml) // http://www.oxxx.com/update74.json? Key = value: the 200 request is returned successfully. The data is read in the stream mode. // The json content includes: /** updated version name | description of the new version | Server version number | New Version apk */checkVersion ();}/*** check version number */private void checkVersion () {new Thread () {public void run () {// send a request to obtain data. The parameter is the URL of the Request json // http: // 192.168.13.99: 8080/update. the json test phase is not optimal // only the simulator accesses the computer tomcat Message msg = Message. obtain (); long startTime = System. currentTimeMillis (); try {// 1, encapsulate the url URL url = new URL ("http: // 169.254.178.87: 8080/update. json "); // 2, enable a link HttpURLConnection connection = (HttpURLConnection) url. openConnection (); // 3. Set common request parameters (request header) // request timeout connection. setConnectTimeout (2000); // read timeout connection. setReadTimeout (2000); // The default value is the get Request Method // connection. setRequestMethod ("POST"); // 4. Obtain the request success response code if (connection. getResponseCode () = 200) {// 5. Get the data in the form of a stream. InputStream is = connection. getInputStream (); // 6, replace the stream with a String (Tool class encapsulation) String json = StreamUtil. streamToString (is); // remember to add permissions --> android. permission. INTERNET Log. I (tag, json); // 7, json parsing JSONObject jsonObject = new JSONObject (json); // debug debugging to Solve the Problem String versionName = jsonObject. getString ("versionName"); mVersionDes = jsonObject. getString ("versionDes"); String versionCode = jsonObject. getString ("versionCode"); mDownloadUrl = jsonObject. getString ("downloadUrl"); // Log print Log. I (tag, versionName); Log. I (tag, mVersionDes); Log. I (tag, versionCode); Log. I (tag, mDownloadUrl); // 8, compare the version number (server version> local version number, prompting the user to update) if (mLocalVersionCode <Integer. parseInt (versionCode) {// prompt for user updates. the pop-up dialog box (UI) and message mechanism msg are displayed. what = UPDATE_VERSION;} else {// enter the main application interface msg. what = ENTER_HOME ;}}} catch (MalformedURLException e) {e. printStackTrace (); msg. what = URL_ERROR;} catch (IOException e) {e. printStackTrace (); msg. what = IO_ERROR;} catch (JSONException e) {e. printStackTrace (); msg. what = JSON_ERROR;} finally {// specifies the sleep time. If the request network duration exceeds 4 seconds, no processing is performed. // The request network duration is less than 4 seconds, force it to sleep for 4 seconds long endTime = System. currentTimeMillis (); if (endTime-startTime <4000) {try {Thread. sleep (4000-(endTime-startTime);} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace () ;}} mHandler. sendMessage (msg );}};}. start ();}/*** Method for returning the version ** @ return non-0 indicates success */private int getVersionCode () {// 1. manager object packageManager PackageManager pm = getPackageManager (); // 2. obtain the basic information (version name, version number) of the specified package name from the package administrator object. try {PackageInfo packageInfo = pm. getPackageInfo (getPackageName (), 0); // 3. get the version name return packageInfo. versionCode;} catch (Exception e) {e. printStackTrace ();} return 0;}/*** get version name: The ** @ return application version name in the configuration file returns null, indicating an exception */private String getVersionName () {// 1. manager object packageManager PackageManager pm = getPackageManager (); // 2. obtain the basic information (version name, version number) of the specified package name from the package administrator object. try {PackageInfo packageInfo = pm. getPackageInfo (getPackageName (), 0); // 3. get the version name return packageInfo. versionName;} catch (Exception e) {e. printStackTrace ();} return null;}/*** initialize the UI method alt + shift + j */private void initUI () {TV _version_name = (TextView) findViewById (R. id. TV _version_name );}}

 

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.