简体   繁体   中英

Android Service and Http request

I wrote an application with behavior like this: "Android client will run a service to send a request HTTP POST to server, server will return data in JSON and delete it from Database".

Problem I got here is: When i start LoadDataActivity (this activity will start service "GetMessage" to receive data froLm server). If i start LoadDataActivity and finish this activity immediately (Service GetMessage will stop too) , that's mean I sent the HTTP POST to server but I have not receive the JSON result yet, while server deleted it in db, so i lost this data.

Is there anyway to help me fix it, but dont have to keep service still running when finish activity?

What you're doing is a bad idea and you need to change some architecture here.

Just because you sent an HTTP request to a server does not mean that the client will get the response. YOu could lose internet connection. A router can break. Someone can trip over a wire and pull it out. The server could crash after deleting the data but before sending it. It's a bad idea.

If you want to do this, you ought to do 1 of 2 things:

1)Have the client send a 2nd request to the server telling it its ok to delete the data now. Do not do it in one request.

2)Use Lazy Deletion. Rather than actually delete the data, add a column "IsDeleted" to the db. Its default should be 0. After sending the data, set it to 1 rather than deleting it. Then change all queries to the table to only return rows where IsDeleted is 0.

Or 3) 1 and 2 combined. This is the best answer.

As for your direct question- no, there's no way to force the HTTP result to come before an activity is finished. So this needs to be done in a service that is started, not bound. An IntentService would work well, so you could have it automatically terminate itself when the request is done, and it would just start a new instance if another request is pending.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM