It's all done. Thought peace of mind, the result is still a problem!
Log start error, get update information exception ... Debug a bit. Discover Exception:android.os.NetworkOnMainThreadException
This exception is probably meant to be an exception when the main thread is visiting the network. Android's version number prior to 4.0 supports access to the network in the main thread. However, after 4.0, this part of the program was optimized, that is to say, the network code can not be written in the main thread.
Check out the workaround on the web. There are two ways to implement the asynchronous task mechanism in Android, Handler and Asynctask.
Handler mode needs to create a new thread for each task, after the completion of the task through the handler instance to the UI thread to send messages, complete interface updates, such a way for the entire process of control is relatively fine, but there are shortcomings. For example, the code is relatively bloated, and when multiple tasks run at the same time, it is not easy to control the thread precisely.
To simplify the operation. Android1.5 provides the tool class Android.os.AsyncTask. It makes it easier to create asynchronous tasks, and it eliminates the need to write task threads and handler instances to complete the same task.
Here we use the asynctask approach.
First look at the definition of Asynctask:
Public abstract class Asynctask<params, Progress, result> {
Three generic types represent the input parameters run by startup task, the progress of background task runs, and the type of background calculation results, respectively.
On specific occasions. Not all types are used. Assumptions are not being used. able to use Java.lang. Void type substitution.
The operation of Asynctask is divided into four steps
Each step corresponds to a callback method, which should not be called by the application. What developers need to do is implement these methods.
1) Sub-class Asynctask
2) Implement one or more of the following methods defined in Asynctask
OnPreExecute (), the method is called by the UI thread before the actual background operation is run.
Be able to do some preparatory work in the method, such as displaying a progress bar on the interface.
Doinbackground (Params ...) will run immediately after the OnPreExecute method is run. The method runs in a background thread. This will be primarily responsible for running very time-consuming back-office computing work. The ability to invoke the Publishprogress method to update real-time task progress.
The method is an abstract method that the subclass must implement.
Onprogressupdate (Progress ...), after the Publishprogress method is called, the UI thread will call this method to show the progress of the task on the interface, for example, through a progress bar.
OnPostExecute (Result), the OnPostExecute method is called by the UI thread after Doinbackground has finished running. The results of the calculation in the background are passed through the method to the UI thread.
For proper use of the Asynctask class. Here are a few guidelines to follow:
1) The instance of the task must be created in the UI thread
2) The Execute method must be called in the UI thread
3) do not manually call OnPreExecute (), OnPostExecute (Result), Doinbackground (Params ...), Onprogressupdate (Progress ...) These several methods
4) The task can only be run once. Otherwise, an exception will occur when multiple calls are made
The parameters of the Doinbackground method and the OnPostExecute must correspond. These two parameters are specified in the list of generic parameters for the Asynctask declaration. The first is the number of Doinbackground accepted, and the second is the number of parameters that show the progress of the run. The third is the Doinbackground return and the OnPostExecute incoming argument.
The following are the detailed processing methods in the project:
Package Com.liuhao.mobilesafe.engine;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Android.content.context;import Android.os.asynctask;import Com.liuhao.mobilesafe.domain.updateinfo;public class Updateinfoservice {private context context;// Context information for the application Environment public Updateinfoservice (context context) {This.context = context;} The process of communicating with the network is encapsulated in the Doinbackground method of the Serviceinbackground private class Serviceinbackground extends Asynctask<integer, Void, updateinfo>{@Overrideprotected UpdateInfo doinbackground (Integer ... params) {String Path = Context.getresources (). getString (Params[0]); Obtain the corresponding content in the resource file according to urlid UpdateInfo info = new UpdateInfo (); URL url;try {url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); conn.setconnecttimeout (20000); Conn.setrequestmethod ("GET"); InputStream is = Conn.getinputstream (); Get the appropriate file stream for the URL. It should be an XML file stream, which needs to be parsed. Info = Updateinfoparser.getupdateinfo (IS); Parse the XML file stream to get the update information entity} catch (Exception e) {e.Printstacktrace ();} return info;} @Overrideprotected void OnPostExecute (UpdateInfo result) {Super.onpostexecute (result);}} /** * @param urlId * Server resource path corresponding ID * @return Update information * @throws Exception */public UpdateInfo getupdateinfo (int u Rlid) throws Exception {//new serviceinbackground (). Execute (urlId). get (); return new Serviceinbackground (). Execute ( urlId). get ();}}
Finally, it is necessary to state that Asynctask cannot completely replace threads, and that logic that is more complex or that needs to be repeated in the background may require threads to be implemented.
After the exception is resolved. Execute the program again:
Click to enter the program, will pop up the upgrade dialog box:
To view logs:
The user clicks OK:
Click Cancel:
References:
Http://www.cnblogs.com/dawei/archive/2011/04/18/2019903.html
http://daoshud1.iteye.com/blog/1843655
"Side doing Project learning Android" Exception handling: android.os.networkonmainthreadexception--Multithreading issues