Lecture #4 activities & fragments
-
Upload
vitali-pekelis -
Category
Software
-
view
98 -
download
0
Transcript of Lecture #4 activities & fragments
Campus-GuestTechiteasy
Yarkoni
IronSource
Android AcademyWomen Techmakers
~ 2000 members Largest Android Active Community
What Do We Do?
●Android Fundamentals
●Android UI / UX
●Community Hackathon
●Android Performance
●Mentors Program●Active community
Online Lessons
Important:
Watch online lesson
before the meetup!
- Our course: “Developing
Android Apps”goo.gl/u1pxZv
- Optional: Nano Degree
- Optional: “Android Basics” courses
The Course Plan
- Online lesson @ home - Lecture @ Campus- Hands-on @ Campus- Questions @ Facebook
YarkoniAndroid Leader
Ironsource
Android Academy Staff
Yonatan LevinGoogle Developer
Expert & Android @ Gett
Britt BarakAndroid Leader
Figure8
Yossi SegevAndroid Developer
Crave
Mentors program
Community Mentors
Limor Mekaiten
Lecture #4: Activities, Fragments &
LifecyclesKnowing where you are is
important
What’s For Today?● Activity● Fragment● Persisting data● External libraries
Reminder - Listeners / callbacks
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time.Function a
(listener)Function a (listener)
Time
Function a (listener)
Function a (listener)
Trigger
Example - callback interface
Example - CREATE & use callback interface
Activity
Activity - Creation
Java file.AndroidManifest.xml declaration.
Android Studio - Quick tip
Entry Point Java Program?
Entry Point Java Program?public static void main(String[] args)
Entry Point Android?
Entry Point Android?“Activity Lifecycle”
Do not try this at home(It won’t work)
A way to think of the callbacks
Activity Lifecycle
Lifecycle is a sequence of setup and teardown callbacks.
Application lifecycle != Thread lifecycle != activity lifecycle.
User and System determine lifecycle.
Activity Lifecycle
An application normally has several activities.When a new activity starts the old one goes into the
stack (LIFO).3 States:
Resumed - foreground has user focus
Paused - partially visible (in memory)
Stopped - not visible (in memory but can be killed)Activity a
Activity b
Activity c
If BACK button pops from the Stack
What does the HOME button do?
If BACK button pops from the Stack
What does the HOME button do?
onUserLeaveHint()
Activity lifecycle - callbacks
onCreateonResumeonStartonPauseonStoponDestory
Activity life cycle
Determined by the user and the system.
Activity Lifecycle - Corresponding Methods
Entire lifetime.Visible lifetime.Foreground lifetime.
What to do in every state
onCreate & onDestroy will be called at most once.
onPause & onResume can be called a lot.
Foreground
Visible
Background
onPause()
onStop()
onResume()
onStart()
Activity - onCreate()
When: on first creation of activity.What: inflate view, find references, bind data,
initialize one timers.Also has bundle with previous frozen state.
Activity - onStart()
●When: the activity is becoming visible to the user.●What: specific stuff which happens every time.●Called every time.
Activity - onResume()
●When: User interaction.●What: resume drawing start animations add
listeners.●Top of the activity stack.●Always followed by onPause().
Activity - onPause()
●When: resuming a previous activity●What: commit unsaved changes to persistent data,
stop intensive CPU actions but keep drawing, remove listeners.
●Promised by the system.
Activity - onStop()● When: Activity is no longer visible either from
starting a new one or destroying the current one.●What: stop drawing and animations. ●onRestart() may be triggered after onStop().
Activity - onDestroy()● When: final call before dying.●What: Nothing important.●Not promised.●Can be called due to explicit or implicit
destruction. isFinishing() allows us to distinguish.
Example - App Starts for the First Time
Example 2- Phone Call
Example 3 - ?
Example 3 - Configuration Change (rotate)
Activity - Life and death●When is activity “killable”?
○onStop
○OnDestroy
●Where do we save the data?○onPause
●Calling finish() goes directly to onDestroy()
Activity - Rotation● A.K.A configuration change.●Destroyed and re-created.
○re-retrieve all resources, drawables, layouts and strings.
●Requires declaration in manifest per activity and @Override onConfigurationChange() method.
AndroidManifest.xml + SecondActivity.java
Developer Responsibilities● Be aware of lifecycle.
● Unregister/Stop actions before death.
● Save state before death.
Developer Responsibilities Example
Does not crash if the user receives a phone call or switches to another app.
Does not consume valuable system resources when the user is not actively using your app.
Does not lose user’s progress when he leaves and returns to the app.
Does not crash or lose user’s progress on orientation change.
Saving Persistent State
Saving Persistent Data
Shared document-like data (SQL / Contentprovider).User preference (savedInstance / SharedPrefs).
Activity - Data Models● Primitives using <Key, Value> pairs.●@Serializable/@Parcelable.
Saving Persistent DataSharedPrefernces
Example
Get & Set SharedPrefs
Saving Persistent DataSavedInstance Primitive
Example
On the way out
On the way in
Saving Persistent DataSavedInstance Parcelable
Example
Dedicated pojo
Dedicated pojo
Parcelable - How to useMainActivity.java
Parcelable - How to useSecondActivity.java
Shortcut!
SavedInstanceState - IcePick
Icepick - https://github.com/frankiesardo/icepickAnnotation based.
Everything has a Price
SavedInstanceState - TEST it!
Don’t keep activities.
Fragments
Represents an operation or interface within an Activity
Fragments
●Started with android API 11 (Honeycomb).●Sophisticated UI on larger screens.●Modularize code.
○ Receives its own input.
○ Can be added or removed while the activity is running.
○ Has its own lifecycle.
Fragments - Better UI
Fragments - Code Recipe
Must have empty constructor.Use factory design pattern.onCreate receives arguments passed.onCreateView return inflated View.
Fragment - onCreate()
When: creating the fragment.What: Initialize essential component of the fragment
that you want to retain when the fragment is paused or stopped, then resumed.
Fragment - onCreateView()
●When: drawing occurs for the first time.●What: To draw a UI for a fragment, you must return
a view from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI.
Fragment - Lifecycle
Fragment - Activity Lifecycle relation
●Important - Activity drives the fragment.
Fragments1st way
Fragment creation using Factory
Fragment creation using Factory
Fragments2nd way
Fragments - FragmentManager
Interaction with fragments is done via FragmentManager.
Has its own back stack for transactions - addToBackStack().
Fragments - Backstack
●When a user presses backIn an activity any Transaction on the BackStack are poppedfff before the activity finishes itself. Fragment a
Fragment b
Fragment c
Fragment BackStack
Activity B
Activity A
Act
iviti
es B
ackS
tack
FragmentsDifferent UI for Tablets
Fragments - Support Multiple Screens
Smallest width.
Fragment - Passing data between fragments
●Should always occur via the joint parent activity.
Fragments - Passing data between fragments
●Should always occur via the joint parent activity.●Define an interface in the fragment class and
implement it within the activity.●The Fragment captures the interface
implementation in onAttach().●From there you can call interface methods to
communicate to the activity.●To communicate down
getSupportFragmentManager(). findFragmentById().
Activity implements Fragment’s interface
Fragments - Passing data between fragments
Fragment A has reference to Activity
Fragment B has reference to Activity
Fragment Callback to activity
Activity Implementation
Activity
Shortcut!
What is the connection?
Fragments - Passing data between fragments
Otto LibraryEvent bus.
Decouples code.
Communication.
Otto - Recipe
Create a singleton holding an instance of Bus class.Register to bus.Create a method to receive and annotate with
@Subscribe.Publish message to subscribers.Unregister to bus (onStop).
Singleton making Bus accessible to all
Activity - Register to bus
Method to Receive the message
Publish message to Subscribers
DO NOT forget to unregister
Homework:1.Go over Activity &
Fragments.2.Watch Lesson #5 of Udacity.
3.Mid stage Sunshine development.
34th floor
Drive home safe
See you next Sunday!