AndroidOperationQueue


Source link: https://github.com/skyfe79/AndroidOperationQueue

AndroidOperationQueue

AndroidOperationQueue is tiny serial operation queue for Android Development.

Setup Gradle

dependencies {
  ...  compile 'kr.pe.burt.android.lib:androidoperationqueue:0.0.2' 
}

Examples

You can see the examples using AndroidOperationQueue at https://github.com/skyfe79/AndroidOperationQueue/tree/master/examples

Image Download without cache

Image Download with cache

APIs

Add operations

You can add operation by using below methods.

  • addOperation()
  • addOperationAtFirst()
  • addOperationAtTime()
  • addOperationAfterDelay()
AndroidOperationQueue queue = new AndroidOperationQueue("JobQueue");
 queue.addOperation(new Operation() {
  @Override  public void run(AndroidOperationQueue q, Bundle bundle) {

// doing job #1
 
}
 
}
);

queue.addOperation(new Operation() {
  @Override  public void run(AndroidOperationQueue q, Bundle bundle) {

// doing job #2
 
}
 
}
);
  

Remove operations

You can remove operation by using below methods.

  • removeOperation()
  • removeOperations()
  • removeAllOperations()
Operation operation = new Operation() {
  @Override  public void run(AndroidOperationQueue q, Bundle bundle) {

// doing job #n
 
}
 
}
;  queue.addOperation(operation);
  ...  queue.removeOperation(operation);
 

Start & Stop OperationQueue

You can start or stop Android Operation Queue by using below methods.

  • start()
  • stop()

stop() method removes all pending operations that are in operation queue.

AndroidOperationQueue queue = new AndroidOperationQueue("JobQueue");
  // add multiple operations ...
// start queue queue.start();

// stop queue queue.stop();

// you can add operation to same queue. queue.addOperation( ... );
  queue.start();

Share common data among operations via Bundle.

You can share data by using Bundle which is in AndroidOperationQueue. If you want to make operation chain, you want to send some result from the current operation to the next operation. You can add up 1, 2 and 3 by using operation and bundle like below.

queue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue q, Bundle bundle) {

bundle.putInt("sum", 1);

  
}
 
}
);
 queue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue q, Bundle bundle) {

int sum = bundle.getInt("sum");

bundle.putInt("sum", sum + 2);

  
}
 
}
);
 queue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue q, Bundle bundle) {

int sum = bundle.getInt("sum");

bundle.putInt("sum", sum + 3);

  
}
 
}
);
 queue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue q, Bundle bundle) {

int sum = bundle.getInt("sum");

Log.v("SUM", String.format("1+2+3 = %d", sum));

  
}
 
}
);

Output is

V/SUM: 1+2+3 = 6 

Example for downloading images with cache

AndroidOperationQueue downloadQueue = new AndroidOperationQueue("DownloadQueue");
  downloadQueue.stop();
  downloadQueue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue queue, Bundle bundle) {

String url = item.getImageURL();

bundle.putString("url", url);

AndroidOperation.runOnUiThread(new Runnable() {

 @Override

 public void run() {

  holder.image.setImageBitmap(null);

  holder.line.setVisibility(View.INVISIBLE);

  holder.progressBar.setVisibility(View.VISIBLE);

 
}

}
);

  
}
 
}
);
  downloadQueue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue queue, Bundle bundle) {

String url = bundle.getString("url");

if(url == null) {

 queue.stop();

}

 // check the url if there is the url in the memory cache

if(Cache.sharedInstance().hasURLInMemoryCache(url) == true) {

 final Bitmap bitmap = Cache.sharedInstance().getBitmapFromMemoryCache(url);

 if(bitmap != null) {

  AndroidOperation.runOnUiThread(new Runnable() {

@Override

public void run() {

 holder.image.setImageBitmap(bitmap);

 holder.line.setVisibility(View.VISIBLE);

 holder.progressBar.setVisibility(View.INVISIBLE);

}

  
}
);

  queue.stop();

 
}

}

  
}
 
}
);
  downloadQueue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue queue, Bundle bundle) {

 String url = bundle.getString("url");

if(url == null) {

 queue.stop();

}

 //check the url if there is the url in the file cache

if(Cache.sharedInstance().hasURLInFileCache(url) == true) {

 final String path = Cache.sharedInstance().getFilePathFromFileCache(url);

 final Bitmap bitmap = BitmapFactory.decodeFile(path);

  if(bitmap != null) {

  Cache.sharedInstance().putBitmapInMemoryCache(url, bitmap);

  AndroidOperation.runOnUiThread(new Runnable() {

@Override

public void run() {

 holder.image.setImageBitmap(bitmap);

 holder.line.setVisibility(View.VISIBLE);

 holder.progressBar.setVisibility(View.INVISIBLE);

 
}

  
}
);

  queue.stop();

 
}

}

  
}
 
}
);
  downloadQueue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue queue, Bundle bundle) {

 String url = bundle.getString("url");

if(url == null) {

 queue.stop();

}

  // there is no bitmap on memory or file then download bitmap from url.

final Bitmap bitmap = downloadBitmapFromURL(url);

if(bitmap != null) {

 Cache.sharedInstance().putBitmapInMemoryCache(url, bitmap);

 AndroidOperation.runOnUiThread(new Runnable() {

  @Override

  public void run() {

holder.image.setImageBitmap(bitmap);

holder.line.setVisibility(View.VISIBLE);

holder.progressBar.setVisibility(View.INVISIBLE);

  
}

 
}
);

  String path = FileUtils.generateTempFileAtExternalStorage("ImageDownloadWithCache", "temp_", ".jpeg");

 boolean success = saveBitmapToPath(bitmap, path);

 if(success) {

  Cache.sharedInstance().putPathInFileCache(url, path);

 
}

}

  
}
 
}
);
  downloadQueue.start();

Operation Utils

runOnUiThread

If you want to update ui element after some background work, you should do it on main thread(ui thread). AndroidOperation provide convenient class method like below.

queue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue q, Bundle bundle) {

// doing background work

AndroidOperation.runOnUiThread(new Runnable() {

 @Override

 public void run() {

  textView.setText("It's completed");

 
}

}
);

  
}
 
}
);

runOnUiThreadAfterDelay

You can also use main thread after some time like below.

queue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue q, Bundle bundle) {

// doing background work

AndroidOperation.runOnUiThreadAfterDelay(new Runnable() {

 @Override

 public void run() {

  textView.setText("It's completed");

 
}

}
, 1000);

  
}
 
}
);

sleep

You can sleep current opertation thread for some time like below.

queue.addOperation(new Operation() {

  @Override
  public void run(AndroidOperationQueue q, Bundle bundle) {

// doing background work

AndroidOperation.runOnUiThreadAfterDelay(new Runnable() {

 @Override

 public void run() {

  textView.setText("It's completed");

 
}

}
, 1000);

AndroidOperation.sleep(1000);
 // sleep for 1 second.
  
}
 
}
);

MIT License

The MIT License (MIT)

Copyright (c) 2016 Sungcheol Kim, https://github.com/skyfe79/AndroidOperationQueue

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Resources

FastHub is yet another open source GitHub client app but unlike any other app, FastHub built from ground up.

CircleMenu is a simple, elegant menu with a circular layout.

A fast, light-weight and powerful Play Store information fetcher for Android.

This library allows you to fetch various live information from Play Store of your app or any other app of your choice. With just a few lines of code, you can get access to a lot of useful app data fetched fresh from the Play Store.

An Android Library to load your GIF files directly

PermissionsManager library that has base activity and fragment that extend from AppCompatActivity to ease with the handling of runtime permissions.

It's a simple MVP implementation. With this library every developer can integration pattern MVP in him project. To add presenter to Activity or Fragment, the developer need write only one row - setPreseter(ExamplePresenter.class);

This library does support MVP pattern for Activities, Fragments and RecyclerViewAdapter.

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