Here is my post:
I'm trying to make myself as clear as possible:
- Description of the classes in my application
- Description of the code architecture (by the Service and by the Activity)
- Description of what should happen
- Description of what actually happens
- Logcat
- Source code
Description of the application classes
I have in my application:
- a service that launches on boot, managed by the
MAJService
class - an activity that is managed by the
ConsoNRJ
class - a worker class that will get HTML pages over HTTP, called
MAJDonnees
- an helper class that is called
InfosConso
and that will instantiate aMAJDonnees
worker.
Description of the processing
When the Service starts, it will:
- create an
InfosConso
object - this
InfosConso
object will create aMAJDonnees
- this
MAJDonnees
object will do HTTP queries usingHttpU开发者_如何学CRLConnection
The activity does almost the same:
- create an
InfosConso
object - this
InfosConso
object will create aMAJDonnees
- this
MAJDonnees
object will create anAsyncTask
, and then do the HTTP queries usingHttpURLConnection
You can see a graph that might help you understand my code:
code.google.com/p/consonrj/wiki/CodeStructureWhat should happen
Since the Activity and the Service basically run the same code (in the MAJDonnees
class), they should behave exactly the same way: fetch HTML pages and parse them
What actually happens
When ran from the service, the HttpURLConnections
returns a bad result while processing in MAJDonnees
.
The HttpURLConnections
instance called h
gives an invalid HTTP response: h.getResponseCode()
returns -1.
However, if the activity is started, the HTTP connections work while processing in MAJDonnees
, indeede h.getResponseCode()
returns 200 (HTTP 200 OK).
THEN if the Service runs again (it is scheduled to run every x minutes), the HTTP connections work!
Logcat
You can have a logcat of the service first ran, then the activity, then again the service, and see the behavior.
http://pastebin.com/DGc8fym2 I'm sorry it is French, I hope you can still guess! :)Source code
If you want, you can have a look at the whole source at:
code.google.com/p/consonrj/source/browse/#svn/trunkI hope you can help me debug this! My service needs to fetch data from Internet when the device starts and every x hours/days, and shouldn't need the activity to start first!
Thanks.
Thank you very much for your advice Brad.
In fact I have solved the problem myself, by generating more debug verbose in the application.
Actually the activity uses the Compte
class that loads the user credentials from files in the phone memory, and the service didn't. So the service didn't have the user credentials to log onto the HTML page. So the service sent login request with empty credentials, until the activity loaded them.
Now that the service also loads the credentials using the Compte
class, it works well.
I am very sorry I didn't investigate more thoroughly my app.
Thanks anyway Brad! Much appreciated.
精彩评论