public class NativeActivity extends Activity implements SurfaceHolder.Callback2, InputQueue.Callback, ViewTreeObserver.OnGlobalLayoutListener
A typical manifest would look like:
A very simple example of native code that is run by NativeActivity follows. This reads input events from the user and uses OpenGLES to draw into the native activity's window.
Modifier and Type | Field and Description |
---|---|
static String |
META_DATA_FUNC_NAME
Optional meta-that can be in the manifest for this component, specifying
the name of the main entry point for this native activity in the
META_DATA_LIB_NAME native code. |
static String |
META_DATA_LIB_NAME
Optional meta-that can be in the manifest for this component, specifying
the name of the native shared library to load.
|
DEFAULT_KEYS_DIALER, DEFAULT_KEYS_DISABLE, DEFAULT_KEYS_SEARCH_GLOBAL, DEFAULT_KEYS_SEARCH_LOCAL, DEFAULT_KEYS_SHORTCUT, FOCUSED_STATE_SET, RESULT_CANCELED, RESULT_FIRST_USER, RESULT_OK
ACCESSIBILITY_SERVICE, ACCOUNT_SERVICE, ACTIVITY_SERVICE, ALARM_SERVICE, APPWIDGET_SERVICE, AUDIO_SERVICE, BACKUP_SERVICE, BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_OOM_MANAGEMENT, BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_IMPORTANT, BIND_NOT_FOREGROUND, BIND_NOT_VISIBLE, BIND_VISIBLE, BIND_WAIVE_PRIORITY, BLUETOOTH_SERVICE, CLIPBOARD_SERVICE, CONNECTIVITY_SERVICE, CONTEXT_IGNORE_SECURITY, CONTEXT_INCLUDE_CODE, CONTEXT_RESTRICTED, COUNTRY_DETECTOR, DEVICE_POLICY_SERVICE, DISPLAY_SERVICE, DOWNLOAD_SERVICE, DROPBOX_SERVICE, INPUT_METHOD_SERVICE, INPUT_SERVICE, KEYGUARD_SERVICE, LAYOUT_INFLATER_SERVICE, LOCATION_SERVICE, MEDIA_ROUTER_SERVICE, MODE_APPEND, MODE_ENABLE_WRITE_AHEAD_LOGGING, MODE_MULTI_PROCESS, MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, NETWORK_POLICY_SERVICE, NETWORK_STATS_SERVICE, NETWORKMANAGEMENT_SERVICE, NFC_SERVICE, NOTIFICATION_SERVICE, NSD_SERVICE, POWER_SERVICE, SCHEDULING_POLICY_SERVICE, SEARCH_SERVICE, SENSOR_SERVICE, SERIAL_SERVICE, SIP_SERVICE, STATUS_BAR_SERVICE, STORAGE_SERVICE, TELEPHONY_SERVICE, TEXT_SERVICES_MANAGER_SERVICE, THROTTLE_SERVICE, UI_MODE_SERVICE, UPDATE_LOCK_SERVICE, USB_SERVICE, USER_SERVICE, VIBRATOR_SERVICE, WALLPAPER_SERVICE, WIFI_P2P_SERVICE, WIFI_SERVICE, WINDOW_SERVICE
TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_COMPLETE, TRIM_MEMORY_MODERATE, TRIM_MEMORY_RUNNING_CRITICAL, TRIM_MEMORY_RUNNING_LOW, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_UI_HIDDEN
Constructor and Description |
---|
NativeActivity() |
Modifier and Type | Method and Description |
---|---|
boolean |
dispatchKeyEvent(KeyEvent event)
Called to process key events.
|
void |
onConfigurationChanged(Configuration newConfig)
Called by the system when the device configuration changes while your
activity is running.
|
protected void |
onCreate(Bundle savedInstanceState)
Called when the activity is starting.
|
protected void |
onDestroy()
Perform any final cleanup before an activity is destroyed.
|
void |
onGlobalLayout()
Callback method to be invoked when the global layout state or the visibility of views
within the view tree changes
|
void |
onInputQueueCreated(InputQueue queue)
Called when the given InputQueue is now associated with the
thread making this call, so it can start receiving events from it.
|
void |
onInputQueueDestroyed(InputQueue queue)
Called when the given InputQueue is no longer associated with
the thread and thus not dispatching events.
|
void |
onLowMemory()
This is called when the overall system is running low on memory, and
would like actively running process to try to tighten their belt.
|
protected void |
onPause()
Called as part of the activity lifecycle when an activity is going into
the background, but has not (yet) been killed.
|
protected void |
onResume()
Called after
Activity.onRestoreInstanceState(android.os.Bundle) , Activity.onRestart() , or
Activity.onPause() , for your activity to start interacting with the user. |
protected void |
onSaveInstanceState(Bundle outState)
Called to retrieve per-instance state from an activity before being killed
so that the state can be restored in
Activity.onCreate(android.os.Bundle) or
Activity.onRestoreInstanceState(android.os.Bundle) (the Bundle populated by this method
will be passed to both). |
protected void |
onStart()
Called after
Activity.onCreate(android.os.Bundle) — or after Activity.onRestart() when
the activity had been stopped, but is now again being displayed to the
user. |
protected void |
onStop()
Called when you are no longer visible to the user.
|
void |
onWindowFocusChanged(boolean hasFocus)
Called when the current
Window of the activity gains or loses
focus. |
void |
surfaceChanged(SurfaceHolder holder,
int format,
int width,
int height)
This is called immediately after any structural changes (format or
size) have been made to the surface.
|
void |
surfaceCreated(SurfaceHolder holder)
This is called immediately after the surface is first created.
|
void |
surfaceDestroyed(SurfaceHolder holder)
This is called immediately before a surface is being destroyed.
|
void |
surfaceRedrawNeeded(SurfaceHolder holder)
Called when the application needs to redraw the content of its
surface, after it is resized or for some other reason.
|
addContentView, closeContextMenu, closeOptionsMenu, createPendingResult, dismissDialog, dispatchGenericMotionEvent, dispatchKeyShortcutEvent, dispatchPopulateAccessibilityEvent, dispatchTouchEvent, dispatchTrackballEvent, dump, findViewById, finish, finishActivity, finishActivityFromChild, finishAffinity, finishFromChild, getActionBar, getActivityToken, getApplication, getCallingActivity, getCallingPackage, getChangingConfigurations, getComponentName, getCurrentFocus, getFragmentManager, getIntent, getLastNonConfigurationInstance, getLayoutInflater, getLoaderManager, getLocalClassName, getMenuInflater, getParent, getParentActivityIntent, getPreferences, getRequestedOrientation, getSystemService, getTaskId, getTitle, getTitleColor, getVolumeControlStream, getWindow, getWindowManager, hasWindowFocus, invalidateOptionsMenu, isChangingConfigurations, isChild, isDestroyed, isFinishing, isImmersive, isResumed, isTaskRoot, managedQuery, managedQuery, moveTaskToBack, navigateUpTo, navigateUpToFromChild, onActionModeFinished, onActionModeStarted, onActivityResult, onApplyThemeResource, onAttachedToWindow, onAttachFragment, onBackPressed, onChildTitleChanged, onContentChanged, onContextItemSelected, onContextMenuClosed, onCreateContextMenu, onCreateDescription, onCreateDialog, onCreateDialog, onCreateNavigateUpTaskStack, onCreateOptionsMenu, onCreatePanelMenu, onCreatePanelView, onCreateThumbnail, onCreateView, onCreateView, onDetachedFromWindow, onGenericMotionEvent, onKeyDown, onKeyLongPress, onKeyMultiple, onKeyShortcut, onKeyUp, onMenuItemSelected, onMenuOpened, onNavigateUp, onNavigateUpFromChild, onNewIntent, onOptionsItemSelected, onOptionsMenuClosed, onPanelClosed, onPostCreate, onPostResume, onPrepareDialog, onPrepareDialog, onPrepareNavigateUpTaskStack, onPrepareOptionsMenu, onPreparePanel, onRestart, onRestoreInstanceState, onRetainNonConfigurationInstance, onSearchRequested, onTitleChanged, onTouchEvent, onTrackballEvent, onTrimMemory, onUserInteraction, onUserLeaveHint, onWindowAttributesChanged, onWindowStartingActionMode, openContextMenu, openOptionsMenu, overridePendingTransition, recreate, registerForContextMenu, removeDialog, requestWindowFeature, runOnUiThread, setContentView, setContentView, setContentView, setDefaultKeyMode, setFeatureDrawable, setFeatureDrawableAlpha, setFeatureDrawableResource, setFeatureDrawableUri, setFinishOnTouchOutside, setImmersive, setIntent, setPersistent, setProgress, setProgressBarIndeterminate, setProgressBarIndeterminateVisibility, setProgressBarVisibility, setRequestedOrientation, setResult, setResult, setSecondaryProgress, setTitle, setTitle, setTitleColor, setVisible, setVolumeControlStream, shouldUpRecreateTask, showDialog, showDialog, startActionMode, startActivities, startActivities, startActivity, startActivity, startActivityAsUser, startActivityAsUser, startActivityForResult, startActivityForResult, startActivityFromChild, startActivityFromChild, startActivityFromFragment, startActivityFromFragment, startActivityIfNeeded, startActivityIfNeeded, startIntentSender, startIntentSender, startIntentSenderForResult, startIntentSenderForResult, startIntentSenderFromChild, startIntentSenderFromChild, startManagingCursor, startNextMatchingActivity, startNextMatchingActivity, startSearch, stopManagingCursor, takeKeyEvents, triggerSearch, unregisterForContextMenu
applyOverrideConfiguration, attachBaseContext, getResources, getTheme, getThemeResId, setTheme
bindService, bindService, checkCallingOrSelfPermission, checkCallingOrSelfUriPermission, checkCallingPermission, checkCallingUriPermission, checkPermission, checkUriPermission, checkUriPermission, clearWallpaper, createConfigurationContext, createDisplayContext, createPackageContext, createPackageContextAsUser, databaseList, deleteDatabase, deleteFile, enforceCallingOrSelfPermission, enforceCallingOrSelfUriPermission, enforceCallingPermission, enforceCallingUriPermission, enforcePermission, enforceUriPermission, enforceUriPermission, fileList, getApplicationContext, getApplicationInfo, getAssets, getBaseContext, getCacheDir, getClassLoader, getCompatibilityInfo, getContentResolver, getDatabasePath, getDir, getExternalCacheDir, getExternalFilesDir, getFilesDir, getFileStreamPath, getMainLooper, getObbDir, getPackageCodePath, getPackageManager, getPackageName, getPackageResourcePath, getSharedPreferences, getSharedPrefsFile, getWallpaper, getWallpaperDesiredMinimumHeight, getWallpaperDesiredMinimumWidth, grantUriPermission, isRestricted, openFileInput, openFileOutput, openOrCreateDatabase, openOrCreateDatabase, peekWallpaper, registerReceiver, registerReceiver, registerReceiverAsUser, removeStickyBroadcast, removeStickyBroadcastAsUser, revokeUriPermission, sendBroadcast, sendBroadcast, sendBroadcastAsUser, sendBroadcastAsUser, sendOrderedBroadcast, sendOrderedBroadcast, sendOrderedBroadcastAsUser, sendStickyBroadcast, sendStickyBroadcastAsUser, sendStickyOrderedBroadcast, sendStickyOrderedBroadcastAsUser, setWallpaper, setWallpaper, startActivitiesAsUser, startInstrumentation, startService, startServiceAsUser, stopService, stopServiceAsUser, unbindService, unregisterReceiver
getString, getString, getText, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, obtainStyledAttributes, registerComponentCallbacks, unregisterComponentCallbacks
public static final String META_DATA_LIB_NAME
public static final String META_DATA_FUNC_NAME
META_DATA_LIB_NAME
native code. If not specified,
"ANativeActivity_onCreate" is used.protected void onCreate(Bundle savedInstanceState)
Activity
Activity.setContentView(int)
to inflate the
activity's UI, using Activity.findViewById(int)
to programmatically interact
with widgets in the UI, calling
Activity.managedQuery(android.net.Uri , String[], String, String[], String)
to retrieve
cursors for data being displayed, etc.
You can call Activity.finish()
from within this function, in
which case onDestroy() will be immediately called without any of the rest
of the activity lifecycle (Activity.onStart()
, Activity.onResume()
,
Activity.onPause()
, etc) executing.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onCreate
in class Activity
savedInstanceState
- If the activity is being re-initialized after
previously being shut down then this Bundle contains the data it most
recently supplied in Activity.onSaveInstanceState(android.os.Bundle)
. Note: Otherwise it is null.Activity.onStart()
,
Activity.onSaveInstanceState(android.os.Bundle)
,
Activity.onRestoreInstanceState(android.os.Bundle)
,
Activity.onPostCreate(android.os.Bundle)
protected void onDestroy()
Activity
Activity.finish()
on it, or because the system is temporarily destroying
this instance of the activity to save space. You can distinguish
between these two scenarios with the Activity.isFinishing()
method.
Note: do not count on this method being called as a place for
saving data! For example, if an activity is editing data in a content
provider, those edits should be committed in either Activity.onPause()
or
Activity.onSaveInstanceState(android.os.Bundle)
, not here. This method is usually implemented to
free resources like threads that are associated with an activity, so
that a destroyed activity does not leave such things around while the
rest of its application is still running. There are situations where
the system will simply kill the activity's hosting process without
calling this method (or any others) in it, so it should not be used to
do things that are intended to remain around after the process goes
away.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onDestroy
in class Activity
Activity.onPause()
,
Activity.onStop()
,
Activity.finish()
,
Activity.isFinishing()
protected void onPause()
Activity
Activity.onResume()
.
When activity B is launched in front of activity A, this callback will
be invoked on A. B will not be created until A's Activity.onPause()
returns,
so be sure to not do anything lengthy here.
This callback is mostly used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one. This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.
In situations where the system needs more memory it may kill paused
processes to reclaim resources. Because of this, you should be sure
that all of your state is saved by the time you return from
this function. In general Activity.onSaveInstanceState(android.os.Bundle)
is used to save
per-instance state in the activity and this method is used to store
global persistent data (in content providers, files, etc.)
After receiving this call you will usually receive a following call
to Activity.onStop()
(after the next activity has been resumed and
displayed), however in some cases there will be a direct call back to
Activity.onResume()
without going through the stopped state.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onPause
in class Activity
Activity.onResume()
,
Activity.onSaveInstanceState(android.os.Bundle)
,
Activity.onStop()
protected void onResume()
Activity
Activity.onRestoreInstanceState(android.os.Bundle)
, Activity.onRestart()
, or
Activity.onPause()
, for your activity to start interacting with the user.
This is a good place to begin animations, open exclusive-access devices
(such as the camera), etc.
Keep in mind that onResume is not the best indicator that your activity
is visible to the user; a system window such as the keyguard may be in
front. Use Activity.onWindowFocusChanged(boolean)
to know for certain that your
activity is visible to the user (for example, to resume a game).
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onResume
in class Activity
Activity.onRestoreInstanceState(android.os.Bundle)
,
Activity.onRestart()
,
Activity.onPostResume()
,
Activity.onPause()
protected void onSaveInstanceState(Bundle outState)
Activity
Activity.onCreate(android.os.Bundle)
or
Activity.onRestoreInstanceState(android.os.Bundle)
(the Bundle
populated by this method
will be passed to both).
This method is called before an activity may be killed so that when it
comes back some time in the future it can restore its state. For example,
if activity B is launched in front of activity A, and at some point activity
A is killed to reclaim resources, activity A will have a chance to save the
current state of its user interface via this method so that when the user
returns to activity A, the state of the user interface can be restored
via Activity.onCreate(android.os.Bundle)
or Activity.onRestoreInstanceState(android.os.Bundle)
.
Do not confuse this method with activity lifecycle callbacks such as
Activity.onPause()
, which is always called when an activity is being placed
in the background or on its way to destruction, or Activity.onStop()
which
is called before destruction. One example of when Activity.onPause()
and
Activity.onStop()
is called and not this method is when a user navigates back
from activity B to activity A: there is no need to call Activity.onSaveInstanceState(android.os.Bundle)
on B because that particular instance will never be restored, so the
system avoids calling it. An example when Activity.onPause()
is called and
not Activity.onSaveInstanceState(android.os.Bundle)
is when activity B is launched in front of activity A:
the system may avoid calling Activity.onSaveInstanceState(android.os.Bundle)
on activity A if it isn't
killed during the lifetime of B since the state of the user interface of
A will stay intact.
The default implementation takes care of most of the UI per-instance
state for you by calling View.onSaveInstanceState()
on each
view in the hierarchy that has an id, and by saving the id of the currently
focused view (all of which is restored by the default implementation of
Activity.onRestoreInstanceState(android.os.Bundle)
). If you override this method to save additional
information not captured by each individual view, you will likely want to
call through to the default implementation, otherwise be prepared to save
all of the state of each view yourself.
If called, this method will occur before Activity.onStop()
. There are
no guarantees about whether it will occur before or after Activity.onPause()
.
onSaveInstanceState
in class Activity
outState
- Bundle in which to place your saved state.Activity.onCreate(android.os.Bundle)
,
Activity.onRestoreInstanceState(android.os.Bundle)
,
Activity.onPause()
protected void onStart()
Activity
Activity.onCreate(android.os.Bundle)
— or after Activity.onRestart()
when
the activity had been stopped, but is now again being displayed to the
user. It will be followed by Activity.onResume()
.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onStart
in class Activity
Activity.onCreate(android.os.Bundle)
,
Activity.onStop()
,
Activity.onResume()
protected void onStop()
Activity
Activity.onRestart()
, Activity.onDestroy()
, or nothing,
depending on later user activity.
Note that this method may never be called, in low memory situations
where the system does not have enough memory to keep your activity's
process running after its Activity.onPause()
method is called.
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
onStop
in class Activity
Activity.onRestart()
,
Activity.onResume()
,
Activity.onSaveInstanceState(android.os.Bundle)
,
Activity.onDestroy()
public void onConfigurationChanged(Configuration newConfig)
Activity
android.R.attr#configChanges
attribute in your manifest. If
any configuration change occurs that is not selected to be reported
by that attribute, then instead of reporting it the system will stop
and restart the activity (to have it launched with the new
configuration).
At the time that this function has been called, your Resources object will have been updated to return resource values matching the new configuration.
onConfigurationChanged
in interface ComponentCallbacks
onConfigurationChanged
in class Activity
newConfig
- The new device configuration.public void onLowMemory()
ComponentCallbacks
Applications that want to be nice can implement this method to release any caches or other unnecessary resources they may be holding on to. The system will perform a gc for you after returning from this method.
onLowMemory
in interface ComponentCallbacks
onLowMemory
in class Activity
public void onWindowFocusChanged(boolean hasFocus)
Activity
Window
of the activity gains or loses
focus. This is the best indicator of whether this activity is visible
to the user. The default implementation clears the key tracking
state, so should always be called.
Note that this provides information about global focus state, which
is managed independently of activity lifecycles. As such, while focus
changes will generally have some relation to lifecycle changes (an
activity that is stopped will not generally get window focus), you
should not rely on any particular order between the callbacks here and
those in the other lifecycle methods such as Activity.onResume()
.
As a general rule, however, a resumed activity will have window focus... unless it has displayed other dialogs or popups that take input focus, in which case the activity itself will not have focus when the other windows have it. Likewise, the system may display system-level windows (such as the status bar notification panel or a system alert) which will temporarily take window input focus without pausing the foreground activity.
onWindowFocusChanged
in interface Window.Callback
onWindowFocusChanged
in class Activity
hasFocus
- Whether the window of this activity has focus.Activity.hasWindowFocus()
,
Activity.onResume()
,
View.onWindowFocusChanged(boolean)
public boolean dispatchKeyEvent(KeyEvent event)
Activity
dispatchKeyEvent
in interface Window.Callback
dispatchKeyEvent
in class Activity
event
- The key event.public void surfaceCreated(SurfaceHolder holder)
SurfaceHolder.Callback
Surface
, so you should not draw into the Surface here
if your normal rendering will be in another thread.surfaceCreated
in interface SurfaceHolder.Callback
holder
- The SurfaceHolder whose surface is being created.public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
SurfaceHolder.Callback
SurfaceHolder.Callback.surfaceCreated(android.view.SurfaceHolder)
.surfaceChanged
in interface SurfaceHolder.Callback
holder
- The SurfaceHolder whose surface has changed.format
- The new PixelFormat of the surface.width
- The new width of the surface.height
- The new height of the surface.public void surfaceRedrawNeeded(SurfaceHolder holder)
SurfaceHolder.Callback2
SurfaceHolder.Callback.surfaceChanged(android.view.SurfaceHolder, int, int, int)
.surfaceRedrawNeeded
in interface SurfaceHolder.Callback2
holder
- The SurfaceHolder whose surface has changed.public void surfaceDestroyed(SurfaceHolder holder)
SurfaceHolder.Callback
surfaceDestroyed
in interface SurfaceHolder.Callback
holder
- The SurfaceHolder whose surface is being destroyed.public void onInputQueueCreated(InputQueue queue)
InputQueue.Callback
onInputQueueCreated
in interface InputQueue.Callback
public void onInputQueueDestroyed(InputQueue queue)
InputQueue.Callback
onInputQueueDestroyed
in interface InputQueue.Callback
public void onGlobalLayout()
ViewTreeObserver.OnGlobalLayoutListener
onGlobalLayout
in interface ViewTreeObserver.OnGlobalLayoutListener