Android-Task


Source link: https://github.com/vRallev/android-task

Deprecated

This library is deprecated and shouldn't be used anymore. Please use something better like RxJava. No more development will be taking place.

Android-Task

An utility library for Android to run actions in background. It handles orientation changes and delegates results to the visible Activity.

Download

Download the latest version or grab via Gradle:

dependencies {

  compile 'net.vrallev.android:android-task:1.1.7' 
}

Usage

The class TaskExecutor serves as entry point. Your background actions need to extend the class Task. Your callback method needs be annotated with TaskResult and has to accept exactly one result object, which the Task returns. You may want to take a look at the demo.

public class MyActivity extends Activity {

 @Override  protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

int taskId = new MyTask().start(this);
  
}

@TaskResult  public void onResult(Integer result) {

// handle result, this method gets called on the UI thread and only if the activity is visible  
}
 
}
  public class MyTask extends Task<Integer> {

 @Override  protected Integer execute() {

return 5;  
}
 
}

Advanced

You can create your own TaskExecutor instance, if you want to change the behavior.

new Builder()  .setExecutorService(Executors.newSingleThreadExecutor()) // default CachedThreadPool  .setPostResult(PostResult.ON_ANY_THREAD) // default PostResult.UI_THREAD  .build()  .asSingleton();

The TaskExecutor returns an ID. You can restore this ID in onCreate(Bundle savedInstanceState to find your Task.

@Override protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

if (savedInstanceState != null) {

int taskId = savedInstanceState.getInt(TASK_ID_KEY, -1);

MyTask task = TaskExecutor.getInstance().getTask(taskId);

  
}
 
}

A callback method can have a second parameter to get the specific Task instance.

@TaskResult public void onResult(Integer result, MyTask task) {
  // handle result, this method gets called on the UI thread and only if the activity is visible 
}

You can annotate the callback method with a concrete ID, if you want to reuse a Task but provide different callbacks. Attention: If your callback method has an ID, then a Task submitted without an ID won't find this callback method.

public void startTask() {
  Task myTask = new MyTask();
  TaskExecutor.getInstance().execute(myTask, this, "my_id");
 
}
  @TaskResult(id = "my_id") public void onResult(Integer result, MyTask task) {
  // handle result, this method gets called on the UI thread and only if the activity is visible 
}

If you want to submit a Task, which should not return any result and shouldn't invoke any callback method, then extend TaskNoCallback. Compared to a normal Thread the purpose of this class is that you still have access to the Context and can find the Task in the TaskExecutor.

public class SimpleNoCallbackTask extends TaskNoCallback {

  @Override
  protected void executeTask() {

// do anything
  
}
 
}

It's possible to replace the callback, if another Activity or Fragment should handle the result.

public class ReplaceCallbackActivity extends Activity {

@Override
  protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

 List<IntegerTask> tasks = TaskExecutor.getInstance().getAllTasks(IntegerTask.class);

for (IntegerTask task : tasks) {

 task.replaceCallback(this);

}

  
}

@TaskResult
  public void onResult(Integer integer) {

Toast.makeText(this, "Replaced " + integer, Toast.LENGTH_SHORT).show();

  
}
 
}

How it works

The TaskExecutor monitors the state of the Activity. When a Task finished, the TaskExecutor searches the callback method and invokes it on the visible Activity or Fragment.

UI components are only referenced with a WeakReference to avoid memory leaks. If a callback method can't be found or the Activity was already cleared, then the result from the Task is dropped.

Limitations

Your class, which can receive callbacks, must be an instance of Activity, FragmentActivity or Fragment from the support library.

The library uses reflection to find your callback method at runtime. This costs time, but classes are scanned in the background.

License

Copyright 2015 Ralf Wondratschek  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

Resources

Demo project for Mortar / Flow / Dagger2 with Auto Dagger2 and Auto Mortar.

ProgressDialog that waits a minimum time to be dismissed before showing. Once visible, the ProgressDialog will be visible for a minimum amount of time to avoid "flashes" in the UI.

The seeds-libraries project is an attempt to build and publish atomic versions of the Guava Libraries which are too valuable to leave out of any modern development project.

The Expandable RecyclerView is a library written to allow for an expanded view to be attached to each ViewHolder. To allow for full functionality of a normal RecyclerView in both the parent ViewHolder and the expanded child ViewHolder, the recyclerview has been modified to use two types of ViewHolders, a child and a parent with the ability to customize each separately.

Custom fonts without writing code.

Easy way to bind collections to listviews and recyclerviews with the new Android Data Binding framework.

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