Как использовать Native Activity? Можно ли это сочетать с традиционной деятельностью? - PullRequest
7 голосов
/ 18 марта 2011

У меня есть две библиотеки (.so), которые я загружаю в код Java.

Однако есть несколько конкретных операций, которые требуют вызовов Java (Activity) <-> C ++ (. So files).

Можно ли использовать Native Activity для реализации части этих функций?Является ли нативная деятельность чем-то дополнительным к традиционной или мне нужно выбрать, какой тип деятельности я буду использовать?

[РЕДАКТИРОВАТЬ]

есть наборсобытий, которые могут быть обработаны в собственном коде с помощью родной активности

android-ndk / sources / android / native_app_glue / android_native_app_glue.h

enum {
    /**
     * Command from main thread: the AInputQueue has changed.  Upon processing
     * this command, android_app->inputQueue will be updated to the new queue
     * (or NULL).
     */
    APP_CMD_INPUT_CHANGED,

    /**
     * Command from main thread: a new ANativeWindow is ready for use.  Upon
     * receiving this command, android_app->window will contain the new window
     * surface.
     */
    APP_CMD_INIT_WINDOW,

    /**
     * Command from main thread: the existing ANativeWindow needs to be
     * terminated.  Upon receiving this command, android_app->window still
     * contains the existing window; after calling android_app_exec_cmd
     * it will be set to NULL.
     */
    APP_CMD_TERM_WINDOW,

    /**
     * Command from main thread: the current ANativeWindow has been resized.
     * Please redraw with its new size.
     */
    APP_CMD_WINDOW_RESIZED,

    /**
     * Command from main thread: the system needs that the current ANativeWindow
     * be redrawn.  You should redraw the window before handing this to
     * android_app_exec_cmd() in order to avoid transient drawing glitches.
     */
    APP_CMD_WINDOW_REDRAW_NEEDED,

    /**
     * Command from main thread: the content area of the window has changed,
     * such as from the soft input window being shown or hidden.  You can
     * find the new content rect in android_app::contentRect.
     */
    APP_CMD_CONTENT_RECT_CHANGED,

    /**
     * Command from main thread: the app's activity window has gained
     * input focus.
     */
    APP_CMD_GAINED_FOCUS,

    /**
     * Command from main thread: the app's activity window has lost
     * input focus.
     */
    APP_CMD_LOST_FOCUS,

    /**
     * Command from main thread: the current device configuration has changed.
     */
    APP_CMD_CONFIG_CHANGED,

    /**
     * Command from main thread: the system is running low on memory.
     * Try to reduce your memory use.
     */
    APP_CMD_LOW_MEMORY,

    /**
     * Command from main thread: the app's activity has been started.
     */
    APP_CMD_START,

    /**
     * Command from main thread: the app's activity has been resumed.
     */
    APP_CMD_RESUME,

    /**
     * Command from main thread: the app should generate a new saved state
     * for itself, to restore from later if needed.  If you have saved state,
     * allocate it with malloc and place it in android_app.savedState with
     * the size in android_app.savedStateSize.  The will be freed for you
     * later.
     */
    APP_CMD_SAVE_STATE,

    /**
     * Command from main thread: the app's activity has been paused.
     */
    APP_CMD_PAUSE,

    /**
     * Command from main thread: the app's activity has been stopped.
     */
    APP_CMD_STOP,

    /**
     * Command from main thread: the app's activity is being destroyed,
     * and waiting for the app thread to clean up and exit before proceeding.
     */
    APP_CMD_DESTROY,
};

так как я знаю, что часть моего кода (которая должна вызываться после определенного события) написана на C ++, я думаю, что будет лучше обрабатывать это в C ++ через нативную Activity.Однако у меня также есть код, который должен вызываться после обработки событий в Java.

вопрос в том ... могу ли я иметь собственную версию (собственный интерфейс) своей деятельности, которая поможет мне с некоторыми событиями, и традиционнуюJava-интерфейс для этой же деятельности в это же время?

1 Ответ

3 голосов
/ 25 марта 2011

Я бы ответил, что у вас не может быть двух версий кода одного действия.

  • Как бы вы указали это в своем манифесте?

  • В примере, предоставленном Google, комментарий основного довольно явный:

Он работает в своем собственном потоке с собственным циклом обработки событий для получения входных событий и выполнения других действий.

Собственное действие будет обрабатывать все события в цикле while(1) {...}. Смешивание Java и нативных событий будет невозможно.

ИМХО, основной причиной использования нативной активности является пользовательский интерфейс. Если у вас уже есть полнофункциональный пользовательский интерфейс в C ++, вам будет проще и проще использовать нативное действие. Вы по-прежнему можете настроить свое приложение для Android, добавить другую java-активность (не забудьте указать android:hasCode="TRUE" в своем манифесте!). В другом случае использование действия java позволяет полностью использовать пользовательский интерфейс Google и при необходимости вызывать вашу нативную библиотеку.

О вас вопрос производительности, когда вы говорите:

Я думаю, что будет лучше справиться с этим в C ++ через нативную активность

взгляните на это: http://developer.android.com/guide/practices/design/performance.html#native_methods

Надеюсь, это поможет!

...