android how to cancel uploading in Ion
Android Asynchronous Networking and Paradigm Loading
Download
- Maven
- Git
Features
- Kotlin coroutine/suspend back up
- Asynchronously download:
- Images into ImageViews or Bitmaps (animated GIFs supported too)
- JSON (via Gson)
- Strings
- Files
- Java types using Gson
- Easy to employ Fluent API designed for Android
- Automatically cancels operations when the calling Activity finishes
- Manages invocation back onto the UI thread
- All operations return a Futurity and tin be cancelled
- HTTP POST/PUT:
- text/plain
- awarding/json - both JsonObject and POJO
- application/x-www-form-urlencoded
- multipart/form-data
- Transparent usage of HTTP features and optimizations:
- SPDY and HTTP/2
- Caching
- Gzip/Deflate Compression
- Connectedness pooling/reuse via HTTP Connection: keep-alive
- Uses the all-time/stablest connection from a server if it has multiple IP addresses
- Cookies
- View received headers
- Grouping and cancellation of requests
- Download progress callbacks
- Supports file:/, http(s):/, and content:/ URIs
- Request level logging and profiling
- Support for proxy servers like Charles Proxy to practise request analysis
- Based on NIO and AndroidAsync
- Ability to use cocky signed SSL certificates
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 equally y'all whorl to the cease
- Put images from a URLs into ImageViews (twitter profile pictures)
- File Download with Progress Bar Sample
- Get JSON and testify images with the Image Search Sample
More than Examples
Looking for more? Bank check out the examples below that demonstrate some other mutual scenarios. You can also take a look at thirty+ 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 east, JsonObject result) { // do stuff with the result or mistake } });
Post JSON and read JSON
JsonObject json = new JsonObject(); json.addProperty("foo", "bar"); Ion.with(context) .load("http://case.com/mail") .setJsonObjectBody(json) .asJsonObject() .setCallback(new FutureCallback<JsonObject>() { @ Override public void onCompleted(Exception east, JsonObject event) { // practise stuff with the result or error } });
Post application/ten-world wide web-form-urlencoded and read a String
Ion.with(getContext()) .load("https://koush.clockworkmod.com/exam/echo") .setBodyParameter("goop", "noop") .setBodyParameter("foo", "bar") .asString() .setCallback(...)
Mail multipart/form-data and read JSON with an upload progress bar
Ion.with(getContext()) .load("https://koush.clockworkmod.com/examination/echo") .uploadProgressBar(uploadProgressBar) .setMultipartParameter("goop", "noop") .setMultipartFile("annal", "awarding/nothing", new File("/sdcard/filename.cypher")) .asJsonObject() .setCallback(...)
Download a File with a progress bar
Ion.with(context) .load("http://example.com/actually-big-file.zip") // have a ProgressBar go updated automatically with the percentage .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 + " / " + full); } }) .write(new File("/sdcard/actually-big-file.zip")) .setCallback(new FutureCallback<File>() { @ Override public void onCompleted(Exception east, 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 epitome into an ImageView
// This is the "long" way to practise build an ImageView request... it allows you lot 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); // only 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/epitome.png");
The Ion Image load API has the post-obit features:
- Deejay and memory caching
- Bitmaps are held via weak references so memory is managed very efficiently
- ListView Adapter recycling back up
- 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 Time to come<T> extends Cancellable, java.util.concurrent.Future<T> { /** * Set a callback to be invoked when this Time to come completes. * @param callback * @return */ public Future<T> setCallback(FutureCallback<T> callback); } Future<String> string = Ion.with(context) .load("http://instance.com/cord.txt") .asString(); Time to come<JsonObject> json = Ion.with(context) .load("http://example.com/json.json") .asJsonObject(); Future<File> file = Ion.with(context) .load("http://example.com/file.nix") .write(new File("/sdcard/file.zippo")); Hereafter<Bitmap> bitmap = Ion.with(context) .load("http://instance.com/image.png") .intoImageView(imageView);
Cancelling Requests
Futures tin exist 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.become() method that waits for the result of the asking, by blocking if necessary.
JsonObject json = Ion.with(context) .load("http://instance.com/affair.json").asJsonObject().go();
Seamlessly use your own Java classes with Gson
public static form Tweet { public String id; public String text; public String photo; } public void getTweets() throws Exception { Ion.with(context) .load("http://example.com/api/tweets") .equally(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 irksome? Ion lets yous do both global and asking level logging.
To enable information technology globally:
Ion.getDefault(getContext()).configure().setLogging("MyLogs", Log.DEBUG);
Or to enable it on but a single request:
Ion.with(context) .load("http://case.com/affair.json") .setLogging("MyLogs", Log.DEBUG) .asJsonObject();
Log entries will look like this:
D/MyLogs(23153): (0 ms) http://case.com/thing.json: Executing request. D/MyLogs(23153): (106 ms) http://case.com/affair.json: Connecting socket D/MyLogs(23153): (2985 ms) http://example.com/thing.json: Response is not cacheable D/MyLogs(23153): (3003 ms) http://case.com/matter.json: Connection successful
Request Groups
By default, Ion automatically places all requests into a group with all the other requests created past that Activity or Service. Using the cancelAll(Activity) call, all requests still pending can be easily cancelled:
Future<JsonObject> json1 = Ion.with(activeness, "http://instance.com/test.json").asJsonObject(); Time to come<JsonObject> json2 = Ion.with(activeness, "http://example.com/test2.json").asJsonObject(); // subsequently... in activity.onStop @ Override protected void onStop() { Ion.getDefault(activity).cancelAll(activity); super.onStop(); }
Ion as well lets you tag your requests into groups to allow for easy cancellation of requests in that grouping afterward:
Object jsonGroup = new Object(); Object imageGroup = new Object(); Hereafter<JsonObject> json1 = Ion.with(activeness) .load("http://example.com/exam.json") // tag in a custom group .group(jsonGroup) .asJsonObject(); Future<JsonObject> json2 = Ion.with(activeness) .load("http://example.com/test2.json") // use the same custom grouping as the other json request .group(jsonGroup) .asJsonObject(); Future<Bitmap> image1 = Ion.with(activity) .load("http://instance.com/test.png") // for this image request, use a unlike group for images .group(imageGroup) .intoImageView(imageView1); Future<Bitmap> image2 = Ion.with(activity) .load("http://instance.com/test2.png") // same imageGroup every bit earlier .group(imageGroup) .intoImageView(imageView2); // later... to cancel only image downloads: Ion.getDefault(action).cancelAll(imageGroup);
Proxy Servers (similar 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://instance.com/proxied.html") .proxy("mycomputer", 8888) .getString();
Using Charles Proxy on your desktop calculator in conjunction with request proxying will bear witness invaluable for debugging!
Viewing Received Headers
Ion operations return a ResponseFuture, which grant admission to response properties via the Response object. The Response object contains the headers, likewise equally the upshot:
Ion.with(getContext()) .load("http://instance.com/test.txt") .asString() .withResponse() .setCallback(new FutureCallback<Response<String>>() { @ Override public void onCompleted(Exception e, Response<Cord> outcome) { // print the response code, ie, 200 System.out.println(upshot.getHeaders().code()); // impress the Cord that was downloaded System.out.println(event.getResult()); } });
Go 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
In that location's hundreds of apps using ion. Experience gratuitous to contact me or submit a pull asking to add yours to this list.
- AllCast
- Helium
- Repost
- Cloupload
- Binge
- PictureCast
- Eventius
- Plume
- GameRaven
- Run across You There
- Doogles
Source: https://github.com/koush/ion
0 Response to "android how to cancel uploading in Ion"
Post a Comment