모바일개발(Mobile Dev)/안드로이드개발(Android)
how to copy a image from server to device
테크한스
2016. 11. 6. 07:34
반응형
- package com.helloandroid.imagedownload
er ; - import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.URL;
- import java.net.URLConnection;
- import org.apache.http.util.ByteArray
Buffer ; - import android.util.Log;
- public class ImageManager {
- private final String PATH = "/data/data/com.helloandr
oid.imagedownloader/" ; //put the downloaded file here - try {
- Log.d("ImageManager", "download begining");
- Log.d("ImageManager", "download url:" + url);
- Log.d("ImageManager", "downloaded file name:" +fileName);
- /* Open a connection to that URL. */
- /*
- * Define InputStreams to read from the URLConnection.
- */
- /*
- * Read bytes to the Buffer until there is nothing more to read(-1).
- */
- ByteArrayBuffer baf = new ByteArrayBuffer(50);
- int current = 0;
- while ((current = bis.read()) != -1) {
- baf.append((byte) current);
- }
- /* Convert the Bytes read to a String. */
- fos.write(baf.toByteArray());
- fos.close();
- Log.d("ImageManager", "download ready in"
- + " sec");
- Log.d("ImageManager", "Error: " + e);
- }
- }
- }
You can check the downloaded file in emulator's File Explorer (DDMS):
Last step you should check your application's permissions to use internet:
- android.permission.INTERNET
- android.permission.ACCESS_NETWORK_STATE
- android.permission.READ_PHONE_STATE
Modify the AndroidManifest.xml file like this:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.c
om/apk/res/android" - package="com.helloandroid.imagedo
wnloader" - android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon"android:label="@string/app_name">
- <activity android:name=".ImageDownloader"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MA
IN" /> - <category android:name="android.intent.category.
LAUNCHER" /> - </intent-filter>
- </activity>
- </application>
- <uses-sdk android:minSdkVersion="7" />
- <uses-permission android:name="android.permission.INTER
NET" ></uses-permission> - <uses-permission android:name="android.permission.ACCES
S_NETWORK_STATE" ></uses-permission> - <uses-permission android:name="android.permission.READ_
PHONE_STATE" ></uses-permission> - </manifest>
반응형