Tag:inpu cannot connect get Data close imageview Automatic call import undle
construct the parameters of the Asynctack subclass Asynctask<params,progress,result> is an abstract class that is typically used for inheritance, and inheriting asynctask needs to specify the following three generic parameters: Params: The type of the input parameter when the task is started. Progress: The type of the progress value is returned in the background task execution. Result: The type of the result is returned when the background execution task finishes. ------------------------How do I construct a callback method for a asynctask subclass? A complete asynctask usually needs to specify the following methods: 1. Doinbackground: This is the method that the Asynctask subclass must override to asynchronously execute the task that the background thread is about to complete. All of our time-consuming operations will be done in this method. 2. OnPreExecute: Called before the background time-consuming operation is performed, usually by the user completing some initialization operations. 3. OnPostExecute: When Doinbackground () is complete, the system automatically calls this method and passes the value returned by Doinbackground () to the method, which is the result of the processing completion. 4. Onprogressupdate: After calling Publishprogrsss () in the Doinbackground () method to update the execution progress of the task, the method is triggered (the PUBLISHPROGRSSS () must be called first), You can know the progress of the current time-consuming operation. ----------------------------------Additional supplement: 1. Note that the example here inherits the Asynctask<void,void,void>, which takes three generics, defines the Void generics to note that V is uppercase ... 2. Execution order: Onprrreexecute ()--doinbackground ()--onprogressupdate ()--OnPostExecute ().
Asynctask<string,void,bitmap> three parameters are: URL type, progress value type, return value type. This example does not set the progress value for the moment, the URL is set to string type, and because we are loading a Bitmap, the parameter type returned is set to Bitmap. 1. Doinbackground (String...params) comes in a variable-length array, which means that we can pass in more than one parameter (via Execute (), which in turn exists in this array. Now there is only one parameter, so just write a params[0] to take out the corresponding URL. 2. Define a bitmap, which is the bitmap we want to acquire. 3. Define a urlconnection that accesses the network, that is, a network connection object connection. 4. Define an InputStream that is used to get the input stream of the data. 5. Initialize connection:connection = new URL (URL). OpenConnection (); You need to import the jar package yourself: import Java.net.URL; Also need try-catch surround. 6. Get the input stream: is = Connection.getinputstream (); 7. Wrapping the input stream: Bufferedinputstream bis = new Bufferedinputstream (IS); 8. The input stream is parsed by Decodestream () to Bitmap:bitmap = Bitmapfactory.decodestream (bis); 9. Closes the input stream and returns bitmap.
1 Public classImagetestextendsActivity {2 PrivateImageView ImageView;3 PrivateProgressBar ProgressBar;4String URL = "Http://p4.so.qhimgs1.com/sdr/1228_768_/t01f7ed810efbfe800a.jpg";5 6 @Override7 protected voidonCreate (Bundle savedinstancestate) {8 //TODO auto-generated Method Stub9 Super. OnCreate (savedinstancestate);Ten Setcontentview (r.layout.image); OneImageView =(ImageView) Findviewbyid (r.id.image); AProgressBar =(ProgressBar) Findviewbyid (R.id.bar); - -MyAsynctask1 task =NewMyAsynctask1 (); the Task.execute (URL); - - } - + //params: Enter the type of the parameter when the task is started. - //progress: The type of the progress value is returned in the background task execution. + //Result : The type of the result is returned when the background execution task finishes. A classMyAsynctask1extendsAsynctask<string, Void, bitmap> { at @Override - //Asynchronous Initialization - protected voidOnPreExecute () { - //TODO auto-generated Method Stub - Super. OnPreExecute (); - //Show progress bar in progressbar.setvisibility (view.visible); - } to + @Override - protected voidOnPostExecute (Bitmap result) { the //TODO auto-generated Method Stub * Super. OnPostExecute (result); $ progressbar.setvisibility (view.gone);Panax Notoginseng Imageview.setimagebitmap (result); - the } + A @Override the protectedBitmap doinbackground (String ... params) { + //TODO auto-generated Method Stub - $ //Remove the parameter value from the params and pass it to the URL $String URL = params[0]; - //Initialize Parameters -Bitmap Bitmap =NULL; the urlconnection Connection; - InputStream InputStream;Wuyi the Try { -Connection =Newurl (url). OpenConnection (); WuInputStream = Connection.getinputstream ();//Get input stream -Bufferedinputstream bis =NewBufferedinputstream (inputstream); AboutThread.Sleep (3000);//sleep for 3 seconds . $ //parsing the input stream via Decodestream () -Bitmap =Bitmapfactory.decodestream (bis); - inputstream.close (); - bis.close (); A +}Catch(IOException e) { the //TODO auto-generated Catch block - e.printstacktrace (); $}Catch(interruptedexception e) { the //TODO auto-generated Catch block the e.printstacktrace (); the } the returnbitmap; - } in the } the About}
The asynchronous loading of the last lesson is repeated, and it is backward and executed without waiting for the progress bar to be full, and we will find that the progress bar behind the execution is not responding. This is not a bug, but a mechanism implemented by Asynctask. The bottom of the asynctask is through the thread pool. When a thread is not finished, the subsequent thread cannot begin. Our last lesson used the for () loop to perform the update operation of the progress bar, and the next task must not be executed until the for () loop has finished. ---------so, how to solve such a problem? It is simple to keep the life cycle of the asynctask consistent with the activity or fragment life cycle. Go back to ProgressBar, rewrite OnPause (), and Judge Asynctask when the activity executes OnPause (): If Asynctask is not empty and in running state, we are going to cancel the thread: protected void OnPause () {super.onpause (); if (Mtask!=null && mtask.getstatus () ==asynctask.status.running) {Mtask.cancel (true); The}cancle () method simply marks the corresponding asynctask as the cancel state and does not really cancel the execution of the thread. In addition, we have no way to directly and rudely stop a thread in Java, we have to wait for one thread to finish before continuing the operation of other threads. --------------How do you stop the thread quickly? 1. Mark the cancellation status in OnPause (): Mtask.cancel (true); Since we have marked the cancel state, we can monitor this change in Asynctask, and once the current state changes to cancelled, we will jump out of the loop, Ends the current operation immediately, thus ending the entire thread logic. 2. In the Doinbackground () method, add iscancelled () in the for () loop to determine the state of the thread: if (iscancelled ()) break;3. Similarly, similar processing is done in the Onprogressupdate () method: if (iscancelled ()) return; By doing so, we can quickly stop the current thread and pass the processing right to the next asynctask.
1 Public classProgressbartestextendsActivity {2 3 ProgressBar ProgressBar;4 MyAsycnTask2 task;5 @Override6 protected voidonCreate (Bundle savedinstancestate) {7 //TODO auto-generated Method Stub8 Super. OnCreate (savedinstancestate);9 Setcontentview (r.layout.progressbar);TenProgressBar =(ProgressBar) Findviewbyid (R.ID.PROGRESSBAR1); One ATask =NewMyAsycnTask2 (); - Task.execute (); - } the - @Override - protected voidOnPause () { - //TODO auto-generated Method Stub + Super. OnPause (); - if(task!=NULL&&task.getstatus () = =AsyncTask.Status.RUNNING) { +Task.cancel (true);//Cancel () simply marks the corresponding task as the cancel state, not actually canceling the thread execution A } at } - - classMyAsycnTask2extendsAsynctask<void, Integer, void> { - - @Override - protected voidonprogressupdate (Integer ... values) { in //TODO auto-generated Method Stub - //Get Progress Update value to Super. Onprogressupdate (values); + if(iscancelled ()) { - return; the } *Progressbar.setprogress (values[0]); $ }Panax Notoginseng - @Override the protectedvoid Doinbackground (void ... params) { + //TODO auto-generated Method Stub A the //Simulation Progress Update + for(inti = 0; I < 100; i++) { - if(iscancelled ()) { $ Break; $ } - publishprogress (i); - Try { theThread.Sleep (300); -}Catch(interruptedexception e) {Wuyi //TODO auto-generated Catch block the e.printstacktrace (); - } Wu } - return NULL; About } $ } -}
Android Siege Lion Asynctask