• Stars
    star
    7,439
  • Rank 5,198 (Top 0.2 %)
  • Language
    Java
  • License
    Other
  • Created about 12 years ago
  • Updated almost 2 years ago

Reviews

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

Repository Details

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

AndroidAsync

AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request library, check out Ion (it is built on top of AndroidAsync). The typical Android app developer would probably be more interested in Ion.

But if you're looking for a raw Socket, HTTP(s) client/server, and WebSocket library for Android, AndroidAsync is it.

Features

  • Based on NIO. Single threaded and callback driven.
  • All operations return a Future that can be cancelled
  • Socket client + socket server
  • HTTP client + server
  • WebSocket client + server

Download

Download the latest JAR or grab via Maven:

<dependency>
    <groupId>com.koushikdutta.async</groupId>
    <artifactId>androidasync</artifactId>
    <version>(insert latest version)</version>
</dependency>

Gradle:

dependencies {
    compile 'com.koushikdutta.async:androidasync:2.+'
}

Download a url to a String

// url is the URL to download.
AsyncHttpClient.getDefaultInstance().getString(url, new AsyncHttpClient.StringCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, String result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("I got a string: " + result);
    }
});

Download JSON from a url

// url is the URL to download.
AsyncHttpClient.getDefaultInstance().getJSONObject(url, new AsyncHttpClient.JSONObjectCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, JSONObject result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("I got a JSONObject: " + result);
    }
});

Or for JSONArrays...

// url is the URL to download.
AsyncHttpClient.getDefaultInstance().getJSONArray(url, new AsyncHttpClient.JSONArrayCallback() {
    // Callback is invoked with any exceptions/errors, and the result, if available.
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, JSONArray result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("I got a JSONArray: " + result);
    }
});

Download a url to a file

AsyncHttpClient.getDefaultInstance().getFile(url, filename, new AsyncHttpClient.FileCallback() {
    @Override
    public void onCompleted(Exception e, AsyncHttpResponse response, File result) {
        if (e != null) {
            e.printStackTrace();
            return;
        }
        System.out.println("my file is available at: " + result.getAbsolutePath());
    }
});

Caching is supported too

// arguments are the http client, the directory to store cache files,
// and the size of the cache in bytes
ResponseCacheMiddleware.addCache(AsyncHttpClient.getDefaultInstance(),
                                  getFileStreamPath("asynccache"),
                                  1024 * 1024 * 10);

Need to do multipart/form-data uploads? That works too.

AsyncHttpPost post = new AsyncHttpPost("http://myservercom/postform.html");
MultipartFormDataBody body = new MultipartFormDataBody();
body.addFilePart("my-file", new File("/path/to/file.txt");
body.addStringPart("foo", "bar");
post.setBody(body);
AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback(){
        @Override
        public void onCompleted(Exception ex, AsyncHttpResponse source, String result) {
            if (ex != null) {
                ex.printStackTrace();
                return;
            }
            System.out.println("Server says: " + result);
        }
    });

Can also create web sockets:

AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
    @Override
    public void onCompleted(Exception ex, WebSocket webSocket) {
        if (ex != null) {
            ex.printStackTrace();
            return;
        }
        webSocket.send("a string");
        webSocket.send(new byte[10]);
        webSocket.setStringCallback(new StringCallback() {
            public void onStringAvailable(String s) {
                System.out.println("I got a string: " + s);
            }
        });
        webSocket.setDataCallback(new DataCallback() {
            public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
                System.out.println("I got some bytes!");
                // note that this data has been read
                byteBufferList.recycle();
            }
        });
    }
});

AndroidAsync also let's you create simple HTTP servers:

AsyncHttpServer server = new AsyncHttpServer();

List<WebSocket> _sockets = new ArrayList<WebSocket>();

server.get("/", new HttpServerRequestCallback() {
    @Override
    public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
        response.send("Hello!!!");
    }
});

// listen on port 5000
server.listen(5000);
// browsing http://localhost:5000 will return Hello!!!

And WebSocket Servers:

AsyncHttpServer httpServer = new AsyncHttpServer();

httpServer.listen(AsyncServer.getDefault(), port);

httpServer.websocket("/live", new AsyncHttpServer.WebSocketRequestCallback() {
    @Override
    public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
        _sockets.add(webSocket);
        
        //Use this to clean up any references to your websocket
        webSocket.setClosedCallback(new CompletedCallback() {
            @Override
            public void onCompleted(Exception ex) {
                try {
                    if (ex != null)
                        Log.e("WebSocket", "An error occurred", ex);
                } finally {
                    _sockets.remove(webSocket);
                }
            }
        });
        
        webSocket.setStringCallback(new StringCallback() {
            @Override
            public void onStringAvailable(String s) {
                if ("Hello Server".equals(s))
                    webSocket.send("Welcome Client!");
            }
        });
    
    }
});

//..Sometime later, broadcast!
for (WebSocket socket : _sockets)
    socket.send("Fireball!");

Futures

All the API calls return Futures.

Future<String> string = client.getString("http://foo.com/hello.txt");
// this will block, and may also throw if there was an error!
String value = string.get();

Futures can also have callbacks...

Future<String> string = client.getString("http://foo.com/hello.txt");
string.setCallback(new FutureCallback<String>() {
    @Override
    public void onCompleted(Exception e, String result) {
        System.out.println(result);
    }
});

For brevity...

client.getString("http://foo.com/hello.txt")
.setCallback(new FutureCallback<String>() {
    @Override
    public void onCompleted(Exception e, String result) {
        System.out.println(result);
    }
});

More Repositories

1

ion

Android Asynchronous Networking and Image Loading
Java
6,299
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