Loading...

A Pattern to Simplify Multiple Async Waiting for Android

View: 159    Dowload: 0   Comment: 0   Post by: admin   Category: Android   Fields: Other

Download  a-pattern-to-simplify-multiple.zip (157.48 KB)

You need to Sign In to download the file a-pattern-to-simplify-multiple.zip
If you do not have an account then Sign up for free here

Introduction

Provide a multiple-async-waiting operation management pattern for Android.

Background

Commonly, when we have some IO FileDescriptor (File, Pipe, Socket, etc.) to do the async-operation, we have to create a dedicated thread to handle the async waiting. If some modules/components require the async waiting simultaneously, we may have to create multiple threads, these will cause some resource wasting.

To reduce the resource consumption and simplify the multiple-async-waiting management, we will create a pattern/method to handle the async waiting in a single dedicated thread.

Using the Code

This article provides native(C++) implementation & Java implementation.

Native(C++) Implementation

Prepare the looper for Native Implementation
void *looperThreadCallback(void *data) {
    *(ALooper **) data = ALooper_prepare(0);
    ALooper_pollAll(-1, 0, NULL, NULL);     //this function will return when call ALooper_wake
    return NULL;
}

ALooper *createLooper(const char *threadName) {
    ALooper *looper = NULL;
    pthread_t t;
    pthread_create(&t, NULL, looperThreadCallback, &looper);
    pthread_setname_np(t, threadName);
    pthread_detach(t);  //detach the pthread_t, because we don't care the thread termination
    while (looper == NULL) { usleep(0); }   //simple spin wait, because the looper should be ready quickly
    return looper;
}

void createDefaultLooper() {
    g_defaultWaitIOLooper = createLooper("DefaultNativeIO");
}
Native main Function
void *registerWaitForSingleFD(int fd, int events, ALooper_callbackFunc func, 
                              void *data, bool isLongRunListener) {
    LOGD("registerWaitForSingleFD: fd=%d events=%d", fd, events);
    ALooper *looper = NULL;
    if (isLongRunListener) {
        looper = createLooper("LongRunNativeIO");
    } else {
        pthread_once(&g_defaultWaitIOLooper_once_t, createDefaultLooper);
        looper = g_defaultWaitIOLooper;
    }
    ALooper_addFd(looper, fd, 0, events, func, data);
    return looper;
}

void unregisterWaitForSingleFD(void *hWait, int fd) {
    LOGD("unregisterWaitForSingleFD: fd=%d", fd);
    ALooper_removeFd((ALooper *) hWait, fd);
    if (hWait != g_defaultWaitIOLooper) {   //check whether LongRunListener
        ALooper_wake((ALooper *) hWait);    //notify ALooper_pollAll to return
    }
}

Java Implementation

Prepare the looper for Java Implementation
private static final HandlerThread mHandlerThread = new HandlerThread("DefaultJavaIO") {{
    start();
}};
Java main Function
public static WaitIOThreadPool registerWaitForSingleFD(FileDescriptor fd, int events, 
MessageQueue.OnFileDescriptorEventListener listener, boolean isLongRunListener) {
    final Looper looper;
    if (isLongRunListener) {
        looper = new HandlerThread("LongRunJavaIO") {{
            start();
        }}.getLooper();
    } else {
        looper = mHandlerThread.getLooper();
    }
    looper.getQueue().addOnFileDescriptorEventListener(fd, events, listener);
    return new WaitIOThreadPool(looper, isLongRunListener);
}

public void unregisterWaitForSingleFD(FileDescriptor fd) {
    mLooper.getQueue().removeOnFileDescriptorEventListener(fd);
    if (mIsLongRunListener) {
        mLooper.quitSafely();
    }
}

In this way, we can handle the multiple-async-waiting in a single dedicated thread for multiple modules/components.

Points of Interest

  1. Android has provided the threadpool implementation in Java side, so we can execute the async callback(MessageQueue.OnFileDescriptorEventListener) in threadpool instead of inline execution (using by the demo code). Because the inline executation may cause some latency on IO data handling.
  2. You even can utilize the main looper(in the UI thread) as the waitor, then no additional dedicated thread require

A Pattern to Simplify Multiple Async Waiting for Android

Provide a multiple-async-waiting operation management pattern for Android

Posted on 07-03-2018 

Comment:

To comment you must be logged in members.

Files with category

  • Chat App

    Chat App

    View: 130    Download: 3   Comment: 0

    Category: Android     Fields: none

    This is a Chat App for Android mobile. You can make separate chat with you partner. I'm using Mysql Database and Php code and All APIs are develop on PHP (REST APIs). My whatsApp:+918285672453: Email ID: nirbhayiise@gmail.com

  • Tower Defense 3D

    Tower Defense 3D

    View: 123    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    The goal in this game is to protect your territory against the attacking enemies. Place defensive structures on or along their path of attack to prevent them reaching your base. Strategic choice and positioning of defensive elements is an essential...

  • Flap the Bird

    Flap the Bird

    View: 77    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Tap your screen to make the bird fly. While you are flying there are destruction that will stop you. Avoid hitting the floor and flying to high this will deduct your life. You can collect coins and life along the way. For more mobile games and...

  • Bad Santa

    Bad Santa

    View: 95    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This is a simple shooting game where the Bad Santa is shooting the bad snowman and reindeer. You can collect coins and life along the way. For more mobile games and tutorials you can visit this site.

  • Flappy Halloween Game

    Flappy Halloween Game

    View: 86    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Flappy Halloween is a simple game, tap the screen to move the player. Shoot the pumpkin in the ring to gain score. Avoid hitting the flying destructions and falling from the ground. Since the Halloween is coming this game is really perfect to play...

  • Tilt Ball Game

    Tilt Ball Game

    View: 71    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This game is simple you need to tilt your device to make the ball move in your own desired direction. Reach the finish line before the time ends and move to the next level.

  • Tanks Dawn of Steel Game

    Tanks Dawn of Steel Game

    View: 105    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Tanks Dawn of Steel is a shooting game which you have to defend yourself against incoming enemies for as long as you can. For every enemy that you destroy, you will receive a coin as a score. This game will challenge your skills in aiming and...

  • An Experience about Using Webview in Android Studio 3.0

    An Experience about Using Webview in Android Studio 3.0

    View: 178    Download: 0   Comment: 0

    Category: Android     Fields: Other

    I am blogging on ngocminhtran.com (using WordPress platform). Like most websites, I want to write an Android application to help viewers have a lot of great experiences with my blog.

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd