Load something from Internet using URLConnection and ReadableByteChannel, in Thread

Last example show "Load something from Internet using URLConnection and BufferedReader, in Thread". Here is another example using java.nio.channels.ReadableByteChannel.

Read operations are synchronous on a ReadableByteChannel, that is, if a read is already in progress on the channel then subsequent reads will block until the first read completes. It is undefined whether non-read operations will block.

package com.blogspot.android_er.androidinternet;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class MainActivity extends AppCompatActivity {

TextView textResult;

protected void onCreate(Bundle savedInstanceState) {
textResult = (TextView)findViewById(R.id.tresult);

MyThread myThread = new MyThread("http://android-er.blogspot.com", textResult);

class MyThread extends Thread{
String target;
TextView textviewResult;

private Handler handler = new Handler();

public MyThread(String target, TextView textviewResult) {
this.target = target;
this.textviewResult = textviewResult;

public void run() {
String result = "";

URL url = null;
try {
url = new URL(target);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();

ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
ByteBuffer buffer = ByteBuffer.allocate(1024);

while (readableByteChannel.read(buffer) > 0)
result += new String(buffer.array());

} catch (MalformedURLException e) {
} catch (IOException e) {

final String finalResult = result;
handler.post(new Runnable() {
public void run() {
"finished", Toast.LENGTH_LONG).show();

For layout and AndroidManifest.xml, refer to the previous post "Load something from Internet using URLConnection and BufferedReader, in AsyncTask".


Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.
Related Posts
Disqus Comments
© Copyright 2017 GENERAL INFO FOR ANDROID DEVELOPMENT - All Rights Reserved - Template Created by goomsite - Proudly powered by Blogger