multithreading - Interrupt HttpURLConnection request Android -


i creating simple class sends requests using httpurlconnection server , receive responses. want add interrupt() method interrupt current request (imagine request running in asynctask , interrupt() called main thread). there 2 processes takes lot of time , don't know how interrupt them:

  • writing output stream
  • reading input stream

so let's want example interrupt reading input stream read this:

downloadthread = new thread(new runnable() {     @override     public void run() {         try {             buffer = readfully(connection.getinputstream());         } catch( exception e ) {             e.printstacktrace();         }     } }); downloadthread.start(); 

and readfully() method is:

public byte[] readfully(inputstream input) throws ioexception {     byte[] buffer = new byte[8192];     int bytesread;     bytearrayoutputstream output = new bytearrayoutputstream();     while ((bytesread = input.read(buffer)) != -1) {         output.write(buffer, 0, bytesread);     }     return output.tobytearray(); } 

how can stop reading input stream (in other words, downloading) ? stop() method of thread deprecated , cannot used. there written everywhere should regularly check if thread should stopped , stop manually. how can when whole time takes line (if understand well):

connection.getinputstream() 

i think same kind of question unanswered (see comments of solution): how stop httpurlconnection connect on android please, don't refer me rest library. know how handle issue. ;).

connection.getinputstream() return connection established server , client ready start streaming response.

so depends on connection: if you're e.g. downloading large file, (nearly all) of time should spent inside readfully() method while streamed, while if response extremely short of empty readfully() little.

in first case, easiest way "interrupt" set boolean flag , check inside loop.

while ((bytesread = input.read(buffer)) != -1) {     if (cancelled)         return null;      output.write(buffer, 0, bytesread); } 

this "boolean flag" can iscancelled() method if you're implementing inside asynctask's doinbackground() (recommended).

in second case, there's not can do, short of killing thread outright (not recommended @ all).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -