Monday, March 7, 2011

Android Internet How to post a non blocking HTTP request in Android?

By Magesh Kumar   Posted at  4:35 AM   Android No comments


This code fetches content from the web without blocking the UI (runs in the background in a Thread). Once finished, it posts a Handler that is picked up by the UI as soon as possible. 
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();

this example has been provided by chris from androidsnippets Internet|How to make a non blocking HTTP request in Android?
This code fetches content from the web without blocking the UI (runs in the background in a Thread). Once finished, it posts a Handler that is picked up by the UI as soon as possible. 
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;

public class Iconic extends Activity {
    private String html = "";
    private Handler mHandler;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     mHandler = new Handler();
     checkUpdate.start();
    }

    private Thread checkUpdate = new Thread() {
        public void run() {
            try {
                URL updateURL = new URL("http://iconic.4feets.com/update");
                URLConnection conn = updateURL.openConnection();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                int current = 0;
                while((current = bis.read()) != -1){
                    baf.append((byte)current);
                }

                /* Convert the Bytes read to a String. */
                html = new String(baf.toByteArray());
                mHandler.post(showUpdate);
            } catch (Exception e) {
            }
        }
    };

    private Runnable showUpdate = new Runnable(){
        public void run(){
         Toast.makeText(Iconic.this, "HTML Code: " + html,
               Toast.LENGTH_SHORT).show();
        }
    };
}

About the Author

Nulla sagittis convallis arcu. Sed sed nunc. Curabitur consequat. Quisque metus enim, venenatis fermentum, mollis in, porta et, nibh. Duis vulputate elit in elit. Mauris dictum libero id justo.
View all posts by: BT9

0 comments:

Back to top ↑
Connect with Us

What they says

© 2013 MaGeSH 2 help. WP Mythemeshop Converted by BloggerTheme9
Blogger templates. Proudly Powered by Blogger.