• Stars
    star
    6,299
  • Rank 6,332 (Top 0.2 %)
  • Language
    Java
  • License
    Other
  • Created over 11 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Android Asynchronous Networking and Image Loading

Android Asynchronous Networking and Image Loading

Download

Features

Samples

The included documented ion-sample project includes some samples that demo common Android network operations:

  • Twitter Client Sample
    • Download JSON from a server (twitter feed)
    • Populate a ListView Adapter and fetch more data as you scroll to the end
    • Put images from a URLs into ImageViews (twitter profile pictures)
  • File Download with Progress Bar Sample
  • Get JSON and show images with the Image Search Sample

More Examples

Looking for more? Check out the examples below that demonstrate some other common scenarios. You can also take a look at 30+ ion unit tests in the ion-test.

Get JSON

Ion.with(context)
.load("http://example.com/thing.json")
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});

Post JSON and read JSON

JsonObject json = new JsonObject();
json.addProperty("foo", "bar");

Ion.with(context)
.load("http://example.com/post")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
   @Override
    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }
});

Post application/x-www-form-urlencoded and read a String

Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.setBodyParameter("goop", "noop")
.setBodyParameter("foo", "bar")
.asString()
.setCallback(...)

Post multipart/form-data and read JSON with an upload progress bar

Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("archive", "application/zip", new File("/sdcard/filename.zip"))
.asJsonObject()
.setCallback(...)

Download a File with a progress bar

Ion.with(context)
.load("http://example.com/really-big-file.zip")
// have a ProgressBar get updated automatically with the percent
.progressBar(progressBar)
// and a ProgressDialog
.progressDialog(progressDialog)
// can also use a custom callback
.progress(new ProgressCallback() {@Override
   public void onProgress(long downloaded, long total) {
       System.out.println("" + downloaded + " / " + total);
   }
})
.write(new File("/sdcard/really-big-file.zip"))
.setCallback(new FutureCallback<File>() {
   @Override
    public void onCompleted(Exception e, File file) {
        // download done...
        // do stuff with the File or error
    }
});

Setting Headers

Ion.with(context)
.load("http://example.com/test.txt")
// set the header
.setHeader("foo", "bar")
.asString()
.setCallback(...)

Load an image into an ImageView

// This is the "long" way to do build an ImageView request... it allows you to set headers, etc.
Ion.with(context)
.load("http://example.com/image.png")
.withBitmap()
.placeholder(R.drawable.placeholder_image)
.error(R.drawable.error_image)
.animateLoad(spinAnimation)
.animateIn(fadeInAnimation)
.intoImageView(imageView);

// but for brevity, use the ImageView specific builder...
Ion.with(imageView)
.placeholder(R.drawable.placeholder_image)
.error(R.drawable.error_image)
.animateLoad(spinAnimation)
.animateIn(fadeInAnimation)
.load("http://example.com/image.png");

The Ion Image load API has the following features:

  • Disk and memory caching
  • Bitmaps are held via weak references so memory is managed very efficiently
  • ListView Adapter recycling support
  • Bitmap transformations via the .transform(Transform)
  • Animate loading and loaded ImageView states
  • DeepZoom for extremely large images

Futures

All operations return a custom Future that allows you to specify a callback that runs on completion.

public interface Future<T> extends Cancellable, java.util.concurrent.Future<T> {
    /**
     * Set a callback to be invoked when this Future completes.
     * @param callback
     * @return
     */
    public Future<T> setCallback(FutureCallback<T> callback);
}

Future<String> string = Ion.with(context)
.load("http://example.com/string.txt")
.asString();

Future<JsonObject> json = Ion.with(context)
.load("http://example.com/json.json")
.asJsonObject();

Future<File> file = Ion.with(context)
.load("http://example.com/file.zip")
.write(new File("/sdcard/file.zip"));

Future<Bitmap> bitmap = Ion.with(context)
.load("http://example.com/image.png")
.intoImageView(imageView);

Cancelling Requests

Futures can be cancelled by calling .cancel():

bitmap.cancel();
json.cancel();

Blocking on Requests

Though you should try to use callbacks for handling requests whenever possible, blocking on requests is possible too. All Futures have a Future.get() method that waits for the result of the request, by blocking if necessary.

JsonObject json = Ion.with(context)
.load("http://example.com/thing.json").asJsonObject().get();

Seamlessly use your own Java classes with Gson

public static class Tweet {
    public String id;
    public String text;
    public String photo;
}

public void getTweets() throws Exception {
    Ion.with(context)
    .load("http://example.com/api/tweets")
    .as(new TypeToken<List<Tweet>>(){})
    .setCallback(new FutureCallback<List<Tweet>>() {
       @Override
        public void onCompleted(Exception e, List<Tweet> tweets) {
          // chirp chirp
        }
    });
}

Logging

Wondering why your app is slow? Ion lets you do both global and request level logging.

To enable it globally:

Ion.getDefault(getContext()).configure().setLogging("MyLogs", Log.DEBUG);

Or to enable it on just a single request:

Ion.with(context)
.load("http://example.com/thing.json")
.setLogging("MyLogs", Log.DEBUG)
.asJsonObject();

Log entries will look like this:

D/MyLogs(23153): (0 ms) http://example.com/thing.json: Executing request.
D/MyLogs(23153): (106 ms) http://example.com/thing.json: Connecting socket
D/MyLogs(23153): (2985 ms) http://example.com/thing.json: Response is not cacheable
D/MyLogs(23153): (3003 ms) http://example.com/thing.json: Connection successful

Request Groups

By default, Ion automatically places all requests into a group with all the other requests created by that Activity or Service. Using the cancelAll(Activity) call, all requests still pending can be easily cancelled:

Future<JsonObject> json1 = Ion.with(activity, "http://example.com/test.json").asJsonObject();
Future<JsonObject> json2 = Ion.with(activity, "http://example.com/test2.json").asJsonObject();

// later... in activity.onStop
@Override
protected void onStop() {
    Ion.getDefault(activity).cancelAll(activity);
    super.onStop();
}

Ion also lets you tag your requests into groups to allow for easy cancellation of requests in that group later:

Object jsonGroup = new Object();
Object imageGroup = new Object();

Future<JsonObject> json1 = Ion.with(activity)
.load("http://example.com/test.json")
// tag in a custom group
.group(jsonGroup)
.asJsonObject();

Future<JsonObject> json2 = Ion.with(activity)
.load("http://example.com/test2.json")
// use the same custom group as the other json request
.group(jsonGroup)
.asJsonObject();

Future<Bitmap> image1 = Ion.with(activity)
.load("http://example.com/test.png")
// for this image request, use a different group for images
.group(imageGroup)
.intoImageView(imageView1);

Future<Bitmap> image2 = Ion.with(activity)
.load("http://example.com/test2.png")
// same imageGroup as before
.group(imageGroup)
.intoImageView(imageView2);

// later... to cancel only image downloads:
Ion.getDefault(activity).cancelAll(imageGroup);

Proxy Servers (like Charles Proxy)

Proxy server settings can be enabled all Ion requests, or on a per request basis:

// proxy all requests
Ion.getDefault(context).configure().proxy("mycomputer", 8888);

// or... to proxy specific requests
Ion.with(context)
.load("http://example.com/proxied.html")
.proxy("mycomputer", 8888)
.getString();

Using Charles Proxy on your desktop computer in conjunction with request proxying will prove invaluable for debugging!

Viewing Received Headers

Ion operations return a ResponseFuture, which grant access to response properties via the Response object. The Response object contains the headers, as well as the result:

Ion.with(getContext())
.load("http://example.com/test.txt")
.asString()
.withResponse()
.setCallback(new FutureCallback<Response<String>>() {
    @Override
    public void onCompleted(Exception e, Response<String> result) {
        // print the response code, ie, 200
        System.out.println(result.getHeaders().code());
        // print the String that was downloaded
        System.out.println(result.getResult());
    }
});

Get Ion

Maven
<dependency>
   <groupId>com.koushikdutta.ion</groupId>
   <artifactId>ion</artifactId>
   <version>(insert latest version)</version>
</dependency>
Gradle
dependencies {
    compile 'com.koushikdutta.ion:ion:(insert latest version)'
}
Local Checkout (with AndroidAsync dependency)
git clone git://github.com/koush/AndroidAsync.git
git clone git://github.com/koush/ion.git
cd ion/ion
ant -Dsdk.dir=$ANDROID_HOME release install

Jars are at

  • ion/ion/bin/classes.jar
  • AndroidAsync/AndroidAsync/bin/classes.jar

Hack in Eclipse

git clone git://github.com/koush/AndroidAsync.git
git clone git://github.com/koush/ion.git
  • Import the project from AndroidAsync/AndroidAsync into your workspace
  • Import all the ion projects (ion/ion, ion/ion-sample) into your workspace.

Projects using ion

There's hundreds of apps using ion. Feel free to contact me or submit a pull request to add yours to this list.

More Repositories

1

AndroidAsync

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.
Java
7,439
star
2

scrypted

Scrypted is a high performance home video integration and automation platform
TypeScript
3,676
star
3

UniversalAdbDriver

One size fits all Windows Drivers for Android Debug Bridge.
C#
1,961
star
4

Superuser

C
1,421
star
5

vysor.io

Vysor - Mirror and Control your Phone
HTML
1,393
star
6

electron-chrome

JavaScript
971
star
7

UrlImageViewHelper

Android library that sets an ImageView's contents from a url. Manages image downloading, caching, and makes your coffee too.
Java
970
star
8

support-wiki

385
star
9

AnyKernel

AnyKernel is a template for an update.zip that can apply any kernel to any ROM, regardless of ramdisk.
Shell
190
star
10

Widgets

UI widgets I use across my apps.
Java
173
star
11

androidmono

The Mono project ported to Android
C#
148
star
12

EFI-X99

Hackintosh Guide: Gigabyte X99P-SLI, Intel 6950X, Radeon
Rich Text Format
124
star
13

ROMManagerManifest

JavaScript
121
star
14

sqlite-net

C#
109
star
15

boilerplate

Java
97
star
16

quickjs

QuickJS Fork with VSCode debugging support
C
81
star
17

PushSms

Java
80
star
18

android-support-v7-appcompat

61
star
19

quack

JavaScript
57
star
20

Loggy

JavaScript
54
star
21

android_system_core

Android System Core (CM)
C
42
star
22

EFI-SkullCanyon

Shell
35
star
23

AppleMobileDeviceSupport

25
star
24

AndroidNetworkBench

Java
23
star
25

MediaRouterSample

Java
22
star
26

Clear

Java
22
star
27

mvn-repo

20
star
28

scrypted.app

HTML
18
star
29

android_vendor_motorola_sholes

Shell
17
star
30

android_device_motorola_sholes

Shell
17
star
31

DroidXBootstrap

Java
17
star
32

csharp-sqlite

C#
15
star
33

koush.com

SCSS
15
star
34

logpush

JavaScript
14
star
35

Chromecast

Java
14
star
36

android_bionic

Android Bionic Library (cyanogenmod)
C
13
star
37

babel

Java
13
star
38

GrowBox

Java
12
star
39

android_device_htc_inc

C
12
star
40

nothingtoseeheremovealong

Shell
11
star
41

CastResources

11
star
42

CastAPI

Java
11
star
43

vysor-cli

TypeScript
10
star
44

fascinate_initramfs

Shell
10
star
45

CarbonResources

10
star
46

android_vendor_motorola_droidx

C
9
star
47

WindowlessControls

A Windows Mobile UI Framework that allows for quick and easy creation of controls and user interfaces that can target any screen resolution and device type.
C#
9
star
48

android_vendor_samsung_galaxys

Shell
8
star
49

legacy_vendor_koush

Shell
8
star
50

CastSite

JavaScript
8
star
51

adb.clockworkmod.com

CSS
8
star
52

GithubProjects

Embed this script into a webpage to get a real time view of your Github repositories!
JavaScript
8
star
53

release

7
star
54

GoogleVoiceService

Java
7
star
55

Droid2Bootstrap

7
star
56

galaxy-initramfs

7
star
57

android_vendor_htc_inc

Shell
7
star
58

android_device_samsung_epic4g

C
7
star
59

dblinq

C#
7
star
60

dev.vysor.io

CSS
6
star
61

WindowlessControlsTutorial

C#
6
star
62

inkwire.io

JavaScript
6
star
63

Screenshot

Java
6
star
64

android-support

6
star
65

scrypted-unifi-protect

TypeScript
6
star
66

google-play-services_lib

Java
6
star
67

epic4gtouch_initramfs_files

Rust
6
star
68

scratch

Kotlin
6
star
69

TiledMaps

A .NET client for tile servers such as Google Maps and Virtual Earth.
C#
6
star
70

AMD7000Controller.kext

5
star
71

scrypted-vscode-typescript

TypeScript
5
star
72

GoogleVoice

C#
5
star
73

WhilWheatonPermissionFixer

Java
5
star
74

Kexts

5
star
75

dropbox-sdk

Java
5
star
76

OpenGLES

A .NET wrapper for OpenGL ES.
C#
5
star
77

Xaml

C#
4
star
78

AsyncTask

C#
4
star
79

TetherResources

4
star
80

otaxdelta3

C
4
star
81

EFI

My EFI partition my hackintosh
JavaScript
4
star
82

sapphire-open

Build configuration and makefiles that can be used to build Android images for the MyTouch.
Shell
4
star
83

clockworkmod.com

CSS
4
star
84

android_vendor_htc_magic

Build configuration and makefiles that can be used to build Android images for the Magic.
Shell
4
star
85

jenkinsmanifest

CSS
4
star
86

android_vendor_htc_supersonic

Shell
4
star
87

android_external_yaffs2

C
4
star
88

ClockworkModLauncher

Java
4
star
89

TiledMapsTest

C#
4
star
90

SyntaxHighlighter

SyntaxHighlighter fork on git
JavaScript
3
star
91

proprietary_vendor_nvidia

3
star
92

Chips

3
star
93

scrypted-google-home

TypeScript
3
star
94

proprietary_vendor_google

JavaScript
3
star
95

GoogleVoiceRepo

3
star
96

scrypted-sdk

JavaScript
3
star
97

android_device_endeavoru

3
star
98

android_vendor_samsung_fascinate

Shell
3
star
99

scrypted-homekit

TypeScript
3
star
100

InkwireResources

3
star