Starting and Ending Activities
- Starting and Ending Activities
- An activity can be started with startActivity(Intent) if no data needs to
be returned.
- An activity that needs to return data is started with an ActivityResultLauncher
- The status of a finishing activity can be set with setResult.
- The standard result codes are RESULT_OK and RESULT_CANCELED.
User codes are also available.
- If an activity is ended by, e.g., the back button, RESULT_CANCELED is
returned.
- An activity can be ended with finish()
- Sending Data to an Activity
- Any extra data is put into a bundle with the Intent.
- Each item of data has a string identifier, conventionally named according to the package
of the sending activity.
- The data is received in the new activity by getting the intent and extracting the extra
data.
- Getting Data back from an Activity
- An ActivityResultLauncher can be fine tuned for specific uses.
- In a simple form, ActivityResultLauncher is used to start an activity specified
in an Intent, and to provide an onActivityResult method that is run
when the activity ends.
- The started activity can put return data into an Intent, and return a result
code plus the Intent, using setResult(int,Intent).
- The data sent by setResult is received in the ActivityResult of
onActivityResult.
- Sending and Receiving Data (while testing your memory)
- Using Standard Activities
- Android systems come preloaded with standard applications whose activities can be
accessed from your applications.
- Contacts
- Web search
- Camera
- Gallery
- etc.
- ActivityResultLauncher can use standard ActivityResultContracts to
start these activities.
- Using a System Activity (to select a picture)
- Take some photos in your AVD to populate the gallery.
- Use the ActivityResultContracts.GetContent() which takes a content type
String and (in this case) returns a Uri for the selected picture
to display.
- All very easy ...
UseSystemActivity.java
activity_main.xml
Do the usual stuff with the manifest, strings, etc.
- Select a picture to display (and understand the code)