Search This Blog

12 May 2010

Grab content from a URL

First we create a basic project:

    F:\work> mvn archetype:generate -DarchetypeCatalog=http://kallisti.eoti.org:8081/content/repositories/snapshots/archetype-catalog.xml

choose the galatea-archetype plugin
groupId: org.eoti.android
artifactId: URLTest
version: 1.0-SNAPSHOT


    F:\work> cd URLTest
    F:\work\URLTest> mvn clean install

Add this to your AndroidManifest.xml:   
    <uses-permission android:name="android.permission.INTERNET" />

And here's the code for your activity (rename as needed):

public class URLTestActivity extends Activity {
    private Handler handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Toast.makeText(URLTestActivity.this, "Time: " + msg.obj, Toast.LENGTH_SHORT).show();
            }
        };
        Thread t = new Thread(){
            @Override
            public void run() {
                try {
                    URL url = new URL("http://tycho.usno.navy.mil/cgi-bin/timer.pl");
                    URLConnection connection = url.openConnection();
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line = "";
                    String s = "";
                    while( (line = in.readLine()) != null )
                    {
                        int idx = line.indexOf("Pacific Time");
                        if( idx != -1)
                        {
                            s = line.substring(4, idx-1).trim(); // strip off "<BR>" and "Pacific Time"
                        }
                    }
                    Message msg = new Message();
                    msg.obj = s;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    Toast.makeText(URLTestActivity.this, "ERROR: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        };
        t.start();
    }
}

Redeploy (mvn clean install) and launch the app. You should see the time (Pacific Time) displayed as a popup.

No comments:

Post a Comment