The Big Bang survey of traffic caused by Android upload location information

Source: Internet
Author: User

Originally by: The project someone wrote a location upload service, actually has no problem, later did not know when there are a lot of complaints, is open app traffic suddenly ran off a few g, almost will sell the house also mobile phone, many colleagues to find the door, then PM solved, I have no time to understand, Today finally restored this big bug, solved only then found, to be careful that, many problems may test can not be measured out, good products is not easy ah, from product to development to testing need to be cautious. I am still far away, accumulate it.

The process of solving the problem is the process of continuous Baidu. Or the first to put a few summary of the better blog it.

1. The output from eclipse is not sufficient to use the ADB logcat command output to the file.

ADB logcat command line usage

ADB logcat-f >*:s-f > D:\log.txt

-F Bad use, try-D. To set a good filter, or come out a bunch of useless log, I sometimes will not succeed, or ubunt under the grep easy to use.

2. Thread view of DDMS: To be honest, the information is too little, I didn't use it.

The meaning of the various fields of threads in Android Ddms

3. Exception information

06-23 16:35:59.045:w/system.err (14651): Android.os.NetworkOnMainThreadException06-23 16:35:59.050:w/system.err (14651): at Android.os.strictmode$androidblockguardpolicy.onnetwork ( strictmode.java:1148)06-23 16:35:59.050:w/system.err (14651): at Libcore.io.BlockGuardOs.connect (blockguardos.java:84)06-23 16:35:59.050:w/system.err (14651): at Libcore.io.IoBridge.connectErrno (iobridge.java:144)06-23 16:35:59.050:w/system.err (14651): at Libcore.io.IoBridge.connect (iobridge.java:112)06-23 16:35:59.050:w/system.err (14651): at Java.net.PlainSocketImpl.connect (plainsocketimpl.java:192)06-23 16:35:59.050:w/system.err (14651): at Java.net.PlainSocketImpl.connect (plainsocketimpl.java:459)06-23 16:35:59.050:w/system.err (14651): at Java.net.Socket.connect (socket.java:843)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.conn.scheme.PlainSocketFactory.connectSocket ( plainsocketfactory.java:119)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection (Defaultclientconnectionoperator.java : 144)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.impl.conn.AbstractPoolEntry.open ( abstractpoolentry.java:164)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.impl.conn.AbstractPooledConnAdapter.open ( abstractpooledconnadapter.java:119)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.impl.client.DefaultRequestDirector.execute ( defaultrequestdirector.java:360)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.impl.client.AbstractHttpClient.execute ( abstracthttpclient.java:583)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.impl.client.AbstractHttpClient.execute ( abstracthttpclient.java:506)06-23 16:35:59.050:w/system.err (14651): at Org.apache.http.impl.client.AbstractHttpClient.execute ( abstracthttpclient.java:484)06-23 16:35:59.055:w/system.err (14651): at Com.cmcc.wepa.util.NetworkManager.httpConnectOpt (Networkmanager.java : 185)06-23 16:35:59.055:w/system.err (14651): at Com.cmcc.wepa.home.UploadLocationThread.run (Uploadlocationthread.java : 90)06-23 16:35:59.055:w/system.err (14651): at Com.cmcc.wepa.location.LocationUploadService.upload ( locationuploadservice.java:141)06-23 16:35:59.055:w/system.err (14651): at Com.cmcc.wepa.location.locationuploadservice.access$0 ( locationuploadservice.java:94)06-23 16:35:59.055:w/system.err (14651): at Com.cmcc.wepa.location.locationuploadservice$1.handlemessage ( locationuploadservice.java:159)06-23 16:35:59.055:w/system.err (14651): at Android.os.Handler.dispatchMessage (handler.java:102)06-23 16:35:59.055:w/system.err (14651): at Android.os.Looper.loop (looper.java:136)06-23 16:35:59.055:w/system.err (14651): at Android.app.ActivityThread.main (activitythread.java:5314)06-23 16:35:59.055:w/system.err (14651): At Java.lang.reflect.Method.invokeNative (Native Method)06-23 16:35:59.055:w/system.err (14651): at Java.lang.reflect.Method.invoke (method.java:515)06-23 16:35:59.055:w/system.err (14651): at Com.android.internal.os.zygoteinit$methodandargscaller.run ( zygoteinit.java:862)06-23 16:35:59.055:w/system.err (14651): at Com.android.internal.os.ZygoteInit.main (zygoteinit.java:678)06-23 16:35:59.055:w/system.err (14651): at Dalvik.system.NativeStart.main (Native Method)
View Code

Network connection has been reported this anomaly, in fact, had not carefully looked at before, can remember the androidblockguardpolicy.onnetwork, met his words is probably because the network request to anti-missile main thread. The current version of Android does not allow time-consuming operations such as network requests to be placed on the main thread.

4. Ok, almost, to two low-level mistakes, I have committed, today is caught colleague committed, I found an afternoon bug did not find this problem, otherwise there will not be the above 3.

1). Write a thread call forgot to start, that is, No. Start ();

2). In the main thread the silly put. Start () is not the method that calls the class, it is not the thread at all, it is equivalent to the main line execution, not the above problem 3.

5. There is also the start of the service, the display start OnCreate is executed once, multiple start is also, but each start will be executed OnStart (), so what to put in which method to think clearly.

@Override Public voidOnStart (Intent Intent,intStartid) {        //TODO auto-generated Method Stub        Super. OnStart (Intent, Startid); LOG.I ("TEST", "OnStart"); Task=NewTimerTask () {@Override Public voidrun () {//TODO auto-generated Method StubMessage msg =Mhandler.obtainmessage (); Msg.what= 0;            Mhandler.sendmessage (msg);        }        }; Timer.schedule (Task,0, 30000); }
View Code

Like the start Timer task above is placed in the Onsstart, I think it is not very good, because the other page of the service will be displayed several times, so there is no need to create this task every time and put in the timing task. In other words, if you really do this, the next time you execute this function, the original thread task is to wait for the completion of the execution has already started over it? Can't terminate it immediately? There is no ability to verify it now. Such conjecture seems quite reasonable, hehe, waiting for expert advice.

6. Finally, I have to solve the problem: the code in question 5 is the start location upload, of course, the following code is now not necessary because this writing trouble, directly upload the good, why still use handler

it. And don't care about the return value of the upload. However, it is good to study the bug.

The timer above periodically sends a message to handler, and then handler upload upload after judging what field.

    PrivateHandler Mhandler =NewHandler () {@Override Public voidhandlemessage (Message msg) {//TODO auto-generated Method Stub            Super. Handlemessage (msg); LOG.I ("TEST", "Handlemessage msg.what=" +msg.what); if(Msg.what = = 0)            {                //log.i ("TEST", "handlemessage");upload (); }        }    };
View Code

It looks fine, and the upload function calls an uploaded thread for the sub-threading operation. This child thread code

 Public classUploadlocationthreadextendsthread{PrivateHandler Handler; PrivateString MemberID;//User ID    PrivateString memlng;//Longitude    PrivateString Menlat;//Latitude     PublicUploadlocationthread () {} PublicUploadlocationthread (Handler Handler, String MemberID, String memlng, String menlat) {Super();  This. Handler =handler;  This. MemberID =MemberID;  This. MEMLNG =memlng;  This. Menlat =Menlat; }     PublicString Getmemberid () {returnMemberID; }     Public voidSetmemberid (String MemberID) { This. MemberID =MemberID; }     PublicString getmemlng () {returnmemlng; }     Public voidsetmemlng (String memlng) { This. MEMLNG =memlng; }     PublicString Getmenlat () {returnMenlat; }     Public voidSetmenlat (String menlat) { This. Menlat =Menlat; }    //Upload location Information@Override Public voidrun () {Super. Run (); HashMap<string, string> param =NewHashmap<string, string>(); Param.put ("UserId", MemberID); Param.put ("USERLNG", MEMLNG); Param.put ("Userlat", Menlat); Message msg=Handler.obtainmessage (); LOG.I ("TEST", "Uploadlocationthread msg" +msg.what); //Gets the return        Try{String result=networkmanager.getinstance (). httpconnectopt (constant.url_update_location, param); Jsonobject obj=json.parseobject (Result); LOG.I ("TEST", "Uploadlocationthread result=" +result); LOG.I ("TEST", "Uploadlocationthread obj=" +obj); String Code= obj.getstring ("code"); LOG.I ("TEST", "Uploadlocationthread code" +code); if(Code.equals ("0") ) {Msg.what= 1; } Else{msg.what=-1; }        } Catch(Exception e) {e.printstacktrace (); } log.i ("TEST", "uploadlocationthread msg.what end =" +msg.what);    Handler.sendmessage (msg); }}
View Code

Okay, here's the problem, no problem is normal, and then something went wrong because:

The thread in message msg = Handler.obtainmessage (); This initial value logcat print will find that The initial value of the Msg.what is 0, however, the subsequent upload network link anomaly is not processed at all, so the exception of the occasion Handler.sendmessage (msg), the Msg.what = 0, passed to the main thread, go back to see the code in the task, Also msg.what=0 call Update this is OK, but the following Mhandler definition is also msg.what=0 when the upload thread is called, so that the timer task in the normal upload, each time the thread upload an exception may be trapped in a dead loop, Because handler received the timer and the upload thread returned by the Msg.what are all 0. No amount of traffic can play like this.

So, for your own special business, the value of Msg.what is best to be far from the default value. Also, the handler mechanism is clear, the main thread receives the handler mechanism and so on. There is exception handling must fly a variety of situations to think clearly.

So the sub-thread upload results do not need to use handler to send msg feedback. The main thread can only handle the timer, and it is best to change it to a value of 100,200.

The Big Bang survey of traffic caused by Android upload location information

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.