0% found this document useful (0 votes)
40 views59 pages

Course3 Fragments and Executor Sept24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views59 pages

Course3 Fragments and Executor Sept24

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

A guided tour

in Android World
Practical Work
Session 3

23-9-2024

© For internal use


Objectives
…What we will do together

1. Dive into 3. Work in a team


The Android World and make
great apps !

2. Take a look at 4. Share our


an application experiences,
(main structure, tools, to be more
components, efficient
GUI, tools…)

2 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Last Session
Practical Work - Session 2

– XML Layout – Activity


• RelativeLayout – Listener
• ImageView – Toast
• EditText – Intent
• Button – Preferences
– String resources – Menu

3 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
During this session
Multithreading, Network, Fragments, simple ListView

WLMastodon WLMastodon
LoginActivity Activity
Mastodon
API
Tweets
Fragment

Layout XML Layout XML

Mastodon
Executor

4 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Agenda
Practical Work – Session 3

▶ Fragment
– What’s a fragment ?
– Integrate a fragment to build modular UI

▶ Multithreading
– Processes and Threads
– User experience
– Retrieve Tweets

▶ Logs
– Use built-in Log API

▶ Listener Pattern

5 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment

What’s a
Fragment ?

6 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
What’s a Fragment ?

▶ “It’s a small Activity within an Activity”


– Component that represents a behavior or a portion of GUI in an Activity

▶ Added in API 11, use android-support-v4.jar to use Fragment prior HoneyComb


– Instead of using android.app.Fragment, use android.support.v4.app.Fragment

▶ Can have a layout, or just have a behavior to run some specific tasks

▶ Always managed by an Activity, which must be a FragmentActivity


– Prior to API 11, use android.support.v4.app.FragmentActivity instead of
android.app.FragmentActivity

▶ Can be embedded in a XML layout file

▶ Can be managed in code

7 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
What’s a Fragment ? : Design Philosophy
▶ Android introduced fragments primarily to support more dynamic and flexible UI
designs on large screens, such as tablets.

▶ Because a tablet's screen is much larger than a handset, there's more room to
combine and interchange UI components.

▶ Fragments allow such designs without the need for you to manage complex
changes to the view hierarchy.

▶ By dividing the layout of an activity into fragments, you become able to modify
the activity's appearance at runtime and preserve those changes in a back stack
that's managed by the activity.

8 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
What’s a Fragment ? : Design Philosophy
▶ You should design each fragment as a modular and reusable activity component

▶ As each fragment defines its own layout and its own behavior with its own
lifecycle callbacks, you can include one fragment in multiple activities

▶ Modularity to cope with fragmentation

9 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
What’s a Fragment ? : Lifecycle
▶ Like Activity, Fragment has lifecycle to handle events

▶ Three essential states :


– Create View
• Inflate the view to be displayed and return it

– Resumed
• Running, in foreground

– Paused
• Running, but another activity is on top
• Other activity doesn’t cover the entire screen

10 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
What’s a Fragment ? : OnCreateView
▶ The system calls this when it's time for the fragment to draw its
user interface for the first time.

▶ To draw a UI for your 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

11 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
What’s a Fragment ? : onResume/onPause
▶ onResume
– Called just before the fragment is active and displayed to the
user

▶ onPause
– Called as the first indication that the user is leaving the
fragment
– This is usually where you should commit any changes that
should be persisted beyond the current user session (because
the user might not come back).

12 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
What’s a Fragment ? : Lifecycle in your code

from

13 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment

Integrate a Fragment
to build modular UI

14 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment
▶ A fragment is usually used as part of an activity's user interface and
contributes its own layout to the activity.

▶ To provide a layout for a fragment, you must implement the onCreateView()


callback method

▶ For example, here's a subclass of Fragment that loads a layout from the
example_fragment.xml file:

15 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : XML style
▶ Usually, a fragment contributes a portion of UI to the host activity, which is
embedded as a part of the activity's overall view hierarchy. There are two
ways you can add a fragment to the activity layout:
– Declare the fragment inside the activity's layout file.
– Or, programmatically add the fragment to an existing ViewGroup.

16 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : code style
▶ Pretty simple
– Create a transaction
– Make the needed changes
– Commit

▶ For example, if we want to add a Fragment to our UI

▶ Create a FragmentTransaction

▶ Add the Fragment, you need the id of a ViewGroup to add the Fragment view
in it

17 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : retrieve Fragment
▶ Although a Fragment is implemented as an object that's independent from an
Activity and can be used inside multiple activities, a given instance of a
fragment is directly tied to the activity that contains it.

▶ Likewise, your activity can call methods in the fragment by acquiring a


reference to the Fragment from FragmentManager, using findFragmentById()
or findFragmentByTag().

18 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment

WLMastodon WLMastodon
LoginActivity Activity
Mastodon
API
Tweets
Fragment

Layout XML Layout XML

Mastodon
Executor

19 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : sumup
▶ Replace the TextView by a new FrameLayout in the WLMastodonActivity
Layout.

Create new folder called fragments

20 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Add Fragment List with RecyclerView

▶ Select the fragments package


and add a new Fragment with a
List.

▶ This wizard use a popup


that let you change
the names for
the generated files.

21 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Add Fragment List with RecyclerView

▶ First delete PlaceHolder folder


as we will not use it.

▶ Add import worldline.ssm.rd.ux.wltwitter.pojo.Tweet;


▶ Then refactor the generated MyTweetRecyclerViewAdapter in order to use Tweet
object instead of PlaceholderItem object

22 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Add Fragment List with RecyclerView

▶ Fix the constructor of the generated class called MyTweetRecyclerViewAdapter

▶ And the relative ViewHolder classe

23 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Add Fragment List with RecyclerView

▶ Adapt the TweetFragment class to change made on the adapter

24 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : sumup
▶ Use FragmentManager to manage Fragment (add/remove…) WLMastodon
Activity

Tweets
Fragment

Layout XML

25 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading

Processes
&
Threads

26 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Internet permission

▶ Remember, the AndroidManifest is the ID card of your application


– If we need Internet access, that’s where it goes

▶ Prompted to the user at install

▶ If you don’t add this permission, you’ll get a “Permission denied”

27 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Processes and Threads

▶ Applications start with a single thread

▶ All components run in the same process and thread


– Named the “main” thread

▶ If a component from the application starts


– the component starts within the process if there is already a process for the
app

▶ You can create additional threads for any process

▶ Since Android 5.0, there’s a “render” thread dedicated to animations/transitions

28 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Processes and Threads

▶ Two rules to Android's single thread model:


– Do not block the UI thread
– Do not access the Android UI toolkit from outside the UI thread

▶ If you try to reach Internet from UI Thread : NetworkOnMainThreadException

NETWORKONMAINTHREADEXCEPTION
DOCUMENTATION

29 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Processes and Threads : ANR

▶ Main thread dispatches events to the widgets


– So it’s also called the UI thread.
– The interaction with the user is handled within this thread

▶ Your app can slow down


– Work load is high (heavy computation)
– Filesystem or database access
– View hierarchy too complex
– …

▶ If your operation is too long, or the work load too high for more than 5 seconds
– Boom, there goes the ANR (Application Not Responding)

30 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Processes and Threads : ANR

▶ The system displays an ANR if an application cannot respond to user input


– If you need to perform a long-running operation

Do it in a dedicated Thread

▶ In Android, application responsiveness is monitored by the Activity Manager and


Window Manager system services.

▶ ANR are displayed when


– No response to an input event within 5 seconds.
– A BroadcastReceiver hasn't finished executing
within 10 seconds.

BROADCASTRECEIVER
DOCUMENTATION

31 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Processes and Threads : Threads

▶ When you’re in the UI Thread


– Be efficient
– Especially in key life-cycle methods such as onCreate() and onResume()

▶ Potentially long running operations such as network or database operations


must/should be done in a dedicated thread
– Other mechanisms exists

▶ How to create a Thread ?


– Using the java.lang.Thread class
– Using the android.os.AsyncTask class

CURSORLOADER
DOCUMENTATION

32 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Processes and Threads : Threads

▶ You might want to create your own Thread or HandlerThread

▶ Set the thread priority to "background" priority by calling


Process.setThreadPriority() and passing THREAD_PRIORITY_BACKGROUND

▶ You can execute several threads in parallel, or sequentially


– Use an Executor
– Be smart ! EXECUTOR
DOCUMENTATION

33 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Processes and Threads : UI Thread

▶ Be sure that your UI thread does not block while waiting for the worker thread
to complete
– Do not call Thread.wait() or Thread.sleep()

▶ After Thread completion ?


– Your main thread should provide a Handler for the other threads to post back
to upon completion
– Or call runOnUiThread

HANDLER
DOCUMENTATION

34 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading

User
Experience

35 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
User Experience

▶ Generally, 100 to 200ms is the threshold beyond which users will perceive
slowness in an application

Always give feedback to your user (such as with a ProgressBar in your UI)

▶ The feedback must be relevant EXPEDIA APPLICATION

36 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
User Experience

▶ If your application has a time-consuming initial setup phase


– consider showing a splash screen or rendering the main view as quickly as
possible
– indicate that loading is in progress
– fill the information asynchronously

▶ You should indicate somehow that progress is being made, don’t let the user
think the application is frozen

37 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading

Retrieve
Tweets

38 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading

WLMastodon WLMastodon
LoginActivity Activity
Mastodon
API

Layout XML Layout XML

Mastodon
Executor

39 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Retrieve Tweets

▶ Create new package executor and a java class called RetrieveTweetsExecutor


▶ Add a android.os.Handler & a ExecutorService to the class

40 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Retrieve Tweets

▶ Then create a getTweets method in order to:


– Make a async call to MastodonHelper.getTweetsOfUser(login)
– Finally post the tweets to the UI thread via the handler

41 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Multithreading
Retrieve Tweets

▶ In TweetsFragments Class, generate the onStart() method that will create and
launch the executor.

42 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Mastodon pratical work
Multithreading

Create your first Asynchronous request to the Mastodon API

44 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Network security configuration

The Network Security Configuration feature lets apps customize their network
security settings in a safe, declarative configuration file without modifying app
code. These settings can be configured for specific domains and for a specific app.
The key capabilities of this feature are as follows:

▶ Custom trust anchors: Customize which Certificate Authorities (CA) are


trusted for an app's secure connections. For example, trusting particular self-
signed certificates or restricting the set of public CAs that the app trusts.

▶ Debug-only overrides: Safely debug secure connections in an app without


added risk to the installed base.

▶ Cleartext traffic opt-out: Protect apps from accidental usage of cleartext


traffic.

▶ Certificate pinning: Restrict an app's secure connection to particular


certificates.

45 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Add a Network Security Configuration file

The Network Security Configuration feature uses an XML file where you specify the
settings for your app. You must include an entry in the manifest of your app to
point to this file. The following code excerpt from a manifest demonstrates how to
create this entry:

<application android:name=".WLMastodonApplication"

android:networkSecurityConfig="@xml/network_security_config">
<uses-
library android:name="org.apache.http.legacy"
android:required="false"/>

res/xml/network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>

46 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Agenda
Part 2

▶ Fragment
– What’s a fragment ?
– Integrate a fragment to build modular UI

▶ Multithreading
– Processes and Threads
– User experience
– Retrieve Tweets

▶ Logs
– Use built-in Log API

▶ Listener Pattern

47 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Logs

Built-in
Log API

48 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Logs
Built-in Log API
▶ Log is a logging class that you can use in your code to print out messages to the
LogCat.

▶ Common logging methods include:


– v(String, String) (verbose)
– d(String, String) (debug)
– i(String, String) (information)
– w(String, String) (warning)
– e(String, String) (error)

▶ For example:

▶ The LogCat will then output something like:

49 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Logs
Built-in Log API : display
▶ Every Android log message has a tag and a priority associated with it.

▶ The tag of a log message is a short string indicating the system component from
which the message originates (for example, "View" for the view system).

▶ The priority is one of the following character values, ordered from lowest to
highest priority:
– V — Verbose (lowest priority)
– D — Debug
– I — Info
– W — Warning
– E — Error
– F — Fatal
– S — Silent (highest priority, on which nothing is ever printed)

▶ You can obtain a list of tags used in the system, together with priorities, by
running LogCat and observing the first two columns : <priority>/<tag>.

51 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Logs
Built-in Log API : filter output
▶ Here's an example of logcat output that shows that the message relates to
priority level "I" and tag "ActivityManager":

▶ To reduce the log output to a manageable level, you can restrict log output
using filter expressions.

▶ Filter expressions let you indicate to the system the tags-priority combinations
that you are interested in

▶ A filter expression follows this format tag:priority ..., where tag indicates the tag
of interest and priority indicates the minimum level of priority to report for that
tag.

52 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Logs
Built-in Log API : test it

▶ Log results in onPostExecute method

▶ You can iterate over result and log it

▶ Use android.util.Log to do so
– Log.v : verbose
– Log.d : debug
– Log.i : info
– Log.w : warning
– Log.e : error
OTHER LIBRARIES

ANDROLOG
▶ Log.d(“TweetAsyncTask”, tweet.text); SLF4J
ANDROIDLOGGER
LOGBACK
LOG4J

56 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Agenda
Part 2

▶ Fragment
– What’s a fragment ?
– Integrate a fragment to build modular UI

▶ Multithreading
– Processes and Threads
– User experience
– Retrieve Tweets

▶ Logs
– Use built-in Log API

▶ Listener Pattern

57 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : manage AsyncTask
▶ Create a new folder called interfaces and define an interface
TweetChangeListener with one method to send back WLMastodon
the result List<Tweet> to the caller
Activity

Tweets
Fragment

▶ Let the TweetsFragment implement this interface Layout XML

TweetChangeListener

58 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : manage Executor
▶ Pass the listener to the Executor
WLMastodon
Activity

Tweets
Fragment

Layout XML

RetrieveTweetsExecutor(this)

Mastodon
Executor

TweetChangeListener

59 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Fragment
Integrate a Fragment : manage Executor

WLMastodon
Mastodon Executor
Activity

▶ Register the listener in the Executor


RetrieveTweetsExecutor(this)

Tweets
Fragment

Layout XML
▶ Use it in the handler to post the result
to the fragment

onTweetRetrieved TweetChangeListener

60 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Mastodon pratical work
Multithreading

Create your tweets fragment handling your asynchronous


request to the MastodonAPI

61 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Custom Adapter
Create a custom layout

▶ Create a custom layout for our list items

Image Alias UserName

TextView TextView
ImageView

WebView
Button

Content of
Retweet
Tweet

62 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Twitter pratical work
custom layout

Create your first custom layout for your fragment Listview

63 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline
Summary
Practical Work - Session 3

– FragmentManager
– FragmentTransaction
– Thread
– Executor
– Fragment

64 | 9/23/2024 | Maxime Peron, François Julien Ritaine, Yassine Benabbas, François Facon © Worldline

You might also like