The following code shows how to Download Image from a URL.
Manifest xml file
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.java2s.myapplication3.app" > <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="java2s.com" android:theme="@style/AppTheme" > <activity android:name="com.java2s.myapplication3.app.MainActivity" android:label="java2s.com" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Main layout xml file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Download file" android:onClick="startDownload" /> <TextView android:id="@+id/status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="click to start" /> </LinearLayout>
Main Activity Java code
package com.java2s.myapplication3.app; /* w w w . ja v a 2 s . c o m*/ import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import java.net.URL; public class MainActivity extends Activity { private Runnable imageDownloader = new Runnable() { public void run() { try { URL imageUrl = new URL("http", "android.com", "/images/froyo.png"); Bitmap image = BitmapFactory.decodeStream(imageUrl.openStream()); if (image != null) { Log.i("DL", "Successfully retrieved file!"); } else { Log.i("DL", "Failed decoding file from stream"); } } catch (Exception e) { Log.i("DL", "Failed downloading file!"); e.printStackTrace(); } } }; public void startDownload(View source) { new Thread(imageDownloader, "Download thread").start(); TextView statusText = (TextView) findViewById(R.id.status); statusText.setText("Download started..."); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }