Home > Mobile >  Worker thread callback function of the main thread, through fragments onAttach provide the Context?
Worker thread callback function of the main thread, through fragments onAttach provide the Context?

Time:10-10

Consult everybody some problems

Look at android website tutorial, this section to connect to network, this tutorial is to teach you things under the worker thread then displayed on the Activity,

It self-built DownloadCallback abstract classes, and then implement this interface in the MainActivity:
MainActivity extends the Activity implements DownloadCallback

Then create a headless fragments in creating AsyncTask to download, download through the callback function, make the main thread to refresh interface,

The callback class (DownloadCallback implementation), not by a constructor or a Set method for fragments, but inside the fragments onAttach (Context Context) this method, to 1:
MCallback=(DownloadCallback) context;

This is what circumstance, don't understand, their checked, this context is MainActivity, why would the context is MainActivity, the most important thing is why MainActivity can be forced into a callback object,

And the AsyncTask doInBackground method to refresh the schedule, seems to be in a worker thread callback MainActivity function, so that the callback function is in the worker thread to perform? How to do it?

CodePudding user response:

Tutorial address:
https://developer.android.google.cn/training/basics/network-ops/connecting

CodePudding user response:

Questionable code:
@ Override
Public void onAttach (Context Context) {
Super. OnAttach (context);
//Host the Activity will handle callbacks from task.
MCallback=(DownloadCallback) The context;
}

There is a:
connection.connect();
PublishProgress (DownloadCallback. Progress. CONNECT_SUCCESS);
Int responseCode=connection. GetResponseCode ();
If (responseCode!=HttpsURLConnection. HTTP_OK) {
Throw new IOException (" HTTP error code: "+ responseCode);
}
//Retrieve the response body as an InputStream.
Stream=connection. GetInputStream ();
PublishProgress (DownloadCallback. Progress. GET_INPUT_STREAM_SUCCESS, 0);
If (stream!=null) {
//Converts the Stream to the String with the Max length of 500.
Result=readStream (stream, 500);
}

CodePudding user response:

MainActivity first of all, you can be strong to DownloadCallback this can understand, MainActivity is the context can also understand,
OnAttach this way is fragmananger hand in the MainActivity, and will be called immediately after the show, this wouldn't have to explore,

Tutorial only tell you to write this, real combat if like this the last you'll be mad, too messy,
You can take a look at this: https://blog.csdn.net/weimingjue/article/details/88528373
  • Related