Я создал приложение для отображения HTML кода любого веб-сайта, в котором входной поток читается символ за символом в фоновом потоке, а затем этот код передается в виде строки в основной поток и отображается в пользовательском интерфейсе.
Однако для сайтов с большим количеством кода чтение в фоновой ветке занимает много времени и ничего не отображается на экране, пока чтение не закончится.
Я хочу передавать эту информацию главному потоку небольшими группами время от времени, а не передавать целое после завершения чтения , чтобы сделать мое приложение более интерактивным.
Вот соответствующий код:
public class MainActivity extends AppCompatActivity {
//class for downloading contents in background thread
public class DownloadTask extends AsyncTask<String ,Void,String>
{
@Override
protected String doInBackground(String... urls)
{
String result="";
URL url;
HttpURLConnection urlConnection=null;
try {
url=new URL(urls[0]); //convert string to a url
urlConnection= (HttpURLConnection) url.openConnection();
InputStream in=urlConnection.getInputStream();
InputStreamReader reader=new InputStreamReader(in);// passing that stream to reader
int data=reader.read(); //char by char reading
while(data!=-1) //data==-1 is the end of stream
{
char cur=(char)data;
result+=cur;
data=reader.read();//read next char
}
} catch (Exception e) {
e.printStackTrace();
}
return result;//returns info to main thread
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);String s;
TextView textView=findViewById(R.id.textView);
//create object of the class in main thread
DownloadTask downloadTask=new DownloadTask();
try {
s=downloadTask.execute("https://stackoverflow.com"/*or any other url here*/).get();//a url is passed
textView.setText(s);
textView.setMovementMethod(ScrollingMovementMethod.getInstance());/*for making textView scrollable*/
} catch (Exception e) {
textView.setText("Error occurred");
e.printStackTrace();
}
}
}