koush/AndroidAsync


Source link: https://github.com/koush/AndroidAsync

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 client/server, WebSocket, and Socket.IO library for Android, AndroidAsync is it.

Features

  • Based on NIO. One thread, driven by callbacks. Highly efficient.
  • All operations return a Future that can be cancelled
  • Socket client + socket server
  • HTTP client + server
  • WebSocket client + server
  • Socket.IO client

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);

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 supports socket.io (version 0.9.x)

SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), "http://192.168.1.2:3000", new ConnectCallback() {

  @Override
  public void onConnectCompleted(Exception ex, SocketIOClient client) {

if (ex != null) {

 ex.printStackTrace();

 return;

}

client.setStringCallback(new StringCallback() {

 @Override

 public void onString(String string) {

  System.out.println(string);

 
}

}
);

client.on("someEvent", new EventCallback() {

 @Override

 public void onEvent(JSONArray argument, Acknowledge acknowledge) {

  System.out.println("args: " + arguments.toString());

 
}

}
);

client.setJSONCallback(new JSONCallback() {

 @Override

 public void onJSON(JSONObject json) {

  System.out.println("json: " + json.toString());

 
}

}
);

  
}
 
}
);

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);

}

  
}
);

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:

server.websocket("/live", new 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", "Error");

  
}
 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);

  
}
 
}
);

Note on SSLv3

https://github.com/koush/AndroidAsync/issues/174

Resources

SerializableParcelableGeneratorPlugin for IntelliJ IDEA & Android Studio to generator SerializableParcelable code.

MaterialDialogBottomSheet is a custom dialog implementation to use BottomSheet MaterialView feature of Lollipop in older versions

Pulls notifications from a remote JSON file and shows them in your app.

Android progress bar with cool animation.

A demo usage of Fresco to show how to load images.

Aeromock is an application server that generates HTML from template files and data files. It enables speedy frontend development without the need for server side modules. Aeromock is referred to as a lightweight mock web application server.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes