SlideShare a Scribd company logo
1 of 81
Android Academy
Session #3
Yonatan Levin
Activities and Intents
3
First,
Yonatan Levin
levin.yonatan
parahall
~ 2000 members Largest Android Active Community
Jonathan Yarkoni
Android Developer & Advocate
Ironsource
Android Academy Staff
Yonatan Levin
Google Developer Expert &
Android @ Gett
Britt Barak
Android Lead
Figure8
Yossi Segev
Android Developer
Crave
What Do We Do?
●Android Fundamentals
●Android UI / UX
●Community Hackathon
●Android Performance
●Mentors Program
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
facebook.com/groups/android.academy.ils
Community Mentors
Roman Smirnov
Questions?
What’s For Today?
● Listeners
● Toasts
● Intents, StartActivity, Navigation
● SharedPreferences
I ❤ Today’s Lecture!
In this lecture, besides the Android stuff,
we will show-case 2 design patterns:
Hidden Agenda for Today
The Observer Pattern
The Static Factory Method Pattern
Design Patterns will be in Purple slides.
Design patterns will get this background.
If you don’t know design patterns,
it’s never too late to learn.
Sources
a CLASSic
A Java Moment
-
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();
Consider this Crazy java codeline
Nested Classes
In Java, a class (or interface) can be declared inside another class.
class A{
class B{
// ...
}
}
Read more: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Inside C, you can use A.B:
class C{
A.B abMember;
A.B doSomething(){ /* … */ }
}
Nested Classes
There are 2 types of nested classes:
class A{
// This one is called a static nested class.
static class B{
// ...
}
// This one is called an inner class - because there’s no static.
class B{
// ...
}
}
Read more: https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
Nested Classes - a Map
Read more: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
Nested Class
Static Nested
Class
Inner Class
Local class
Anonymous
Class
Examples:
ViewHolder
AsyncTask
Examples:
Runnable
OnClick
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();
Consider this Crazy java codeline
Our Starting Point
in activity_main.xml:
<Button
android:text="Hooking to buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="goToButtonsDemo"
/>
In MainActivity.java:
public void goToButtonsDemo(View view) {
Intent i = new Intent(this, ButtonsDemoActivity.class);
startActivity(i);
}
Handling Events
3 ways to listen(er)s
Way #1: android:onClick=”...” in xml
In activity_buttons_demo.xml declare the button with an OnClick:
<Button
android:text="Red +"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="increaseRed"
android:background="@color/lightred"
/>
In ButtonsDemoActivity.java, implement the method that will be called
public void increaseRed(View view) {
// ...
}
Way #2: Inline OnClickListener
In the Activity’s onCreate method, grab the buttons and set their
OnClickListener with an inline implementation
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
Button increaseGreen = (Button)findViewById(R.id.buttonsdemo_incGreen);
increaseGreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ...
}
});
}
Way #3: Single OnClickListener
(1) Make the activity implement View.OnClickListener:
public class ButtonsDemoActivity extends ActionBarActivity
implements View.OnClickListener
(2) In OnCreate, set the button’s listener to the activity (with this):
@Override
protected void onCreate(Bundle savedInstanceState) {
// …
Button decreaseRed = (Button)findViewById(R.id.buttonsdemo_decRed);
decreaseRed.setOnClickListener(this);
}
Way #3: Single OnClickListener
(3) Implement the interface, use a switch to tell which button view
was clicked:
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonsdemo_decRed:
red = calcNewValue(red, -1);
break;
case R.id.buttonsdemo_decGreen:
green = calcNewValue(green, -1);
break;
case R.id.buttonsdemo_decBlue:
blue = calcNewValue(blue, -1);
break;
}
refreshDisplay();
Demo: The Color Mixer
1 Button: Way #1
2 Buttons: Way #2
3 Buttons: Way #3
Not really 3 ways...
In fact, there’s only one way to have a button do something:
Set a View.OnClickListener.
Way #1 does this implicitly,
and ways 2,3 does this explicitly.
What is a listener?
Listener: an interface that contains a single callback method.
When the user interacts with the UI, the Views trigger a call to the
listener (if it’s not null) and calls the callback.
As long as the view and the listener agrees on the contract between
them (~ The method’s signature), the view doesn’t care what the
implementation is.
This is a great example of the Observer design pattern.
Source: http://developer.android.com/guide/topics/ui/ui-events.html#EventListeners
The Observer Design Pattern
A Behavioral design pattern, commonly used in UI (but not only).
Read a lot more: https://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Observer
View.OnClickListener
View
Your Listener
How does xml onClick (way #1) work
When you use the xml’s onClick way,
the View uses a View.DeclaredOnClickListener,
It uses reflection (which is slow on android),
but It’s Lazy and Cached,
and is not validated at Compile-Time.
Since android is Open-Source, check out the implementation at the
link below.
https://github.com/android/platform_frameworks_base/blob/master/core/java/android/view/View.java Line
4429
Which is better?
Way #1: onClick=”...” → DeclaredOnClickListener
Way #2: inline listener implementation
Way #3: activity interface implementation
http://stackoverflow.com/questions/21319996/android-onclick-in-xml-vs-onclicklistener
Pros: Clean code, no findViewById at all
Cons: Reflection, No Compile-Time validation, API Level ≥ 4, not readable
Pros: Readable code
Cons: +1 class, +1 method, ~500 bytes, +Boilerplate code, if you have a lot of clicks
becomes mess
Pros: No object allocations
Cons: Felix: The horrible switch (over view.getId())
What other listeners are available?
Read more: http://developer.android.com/guide/topics/ui/ui-events.html
Event Handler
onClick View.OnClickListener
onLongClick View.OnLongClickListener
onFocusChange
View.OnFocusChangeListener
onKey View.OnKeyListener
onTouch View.OnTouchListener
onCreateContextMenu View.OnCreateContextMenuListener
AdapterView.OnItemClickListener
Non-void Listeners
Some flows requires listeners to tell
when they take care of the event.
These listeners return a boolean:
true if the event is consumed,
or false if it isn’t.
onTouchListener is a good example.
OnClick || OnTouch?
OnTouch gets called on any change in the touch detection,
and contains touch data. The MotionEvent is passed to the root view,
and it travels until it finds an OnTouchListener that would handle it.
Some may react to the event without consuming it - common practice
for when using Gesture Detectors.
For “Everyday tapping” - You usually should go with onClick.
Read More: http://codetheory.in/understanding-android-input-touch-events/
Take Aways - Listeners
1.UI Interaction is implemented with Listeners.
2.Some listeners returns a boolean value to indicate handling.
3.OnTouch is really important,
and in most cases, you won’t need it.
And the Static Factory Method pattern
Toasts
B
Toasts
provides simple feedback about an
operation in a small popup.
The current activity remains visible and
interactive - But the toast itself is not
interactive.
Toast disappear after a short time.
http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Make a Toast
Toast.makeText(this,"I'm your father,Luke!",Toast.LENGTH_LONG)
.show();
Toast Positioning
toast.setGravity(Gravity.CENTER|Gravity.RIGHT, 0, 0);
Static Factory Method
●The best ways to create an object.
●Have a name
●Can cache and not always create new class
●They return an object
●Reduce the verbosity of creating parameterized type instances
Read more: http://www.informit.com/articles/article.aspx?p=1216151
Static Factory Method
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
Read more:
Most important thing about Toasts:
show()
Not in course: Snackbars
Defined in the Material Design spec, SnackBars also allow user
interaction - and also work great with FABs -
Both are out-of-scope from our course.
http://developer.android.com/reference/android/support/design/widget/Snackbar.html
If you need user interaction, you can use a notification (which we’ll
see in Session #6)
and if you really need a custom toast design,
you can - but it’s not covered here.
Also not talking about...
- It lets newly created objects understand what has been going on.
- Global information about an application environment
- Creating New objects: Creating new views, adapters, listeners:
TextView tv = new TextView(getContext());
ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
- Accessing Standard Common Resources: Services like
LAYOUT_INFLATER_SERVICE, SharedPreferences:
context.getSystemService(LAYOUT_INFLATER_SERVICE);
getApplicationContext().getSharedPreferences(*name*, *mode*);
- Accessing Components Implicitly: Regarding content providers, broadcasts,
intent: getApplicationContext().getContentResolver().query(uri, ...);
Context - #1 reason of memory leaks
- Further reads: https://possiblemobile.com/2013/06/context/
View svButton = findViewById(R.id.sv_button);
svButton.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
setStaticView();
}
});
public static View view;
void setStaticView() {
view = findViewById(R.id.sv_button);
}
and also a bit about Navigation
Intents and StartActivity
C
Intents
messaging object you can to request an
action from another app component.
Main Use-cases:
- Starting an activity
- Broadcasting a message
- Starting a service (wait for Session 6)
http://developer.android.com/guide/components/intents-filters.html
Intent Types
Explicit Intent - have a ComponentName -
so Android knows exactly what to call.
Implicit Intent, doesn’t have a
ComponentName - so Android uses Intent
Filters to know what to do.
used for Explicit Intents
used for Implicit Intents
used to tell things to the recipient
used to tell things to the messenger
Intents have...
Component Name
Action
Data (and Type)
Category
Extras
Flags
Intent Filters
Intent filters are used to advertise what
intents your app can handle.
We’ve already seen MainActivity’s
intent filter in Session #1.
Read more: http://developer.android.com/guide/components/intents-filters.html#Receiving
Explicitly
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
or
Intent intent = new Intent(getApplicationContext(), TargetActivity.class);
getApplicationContext().startActivity(intent);
Implicitly
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("geo:37.7749,-122.4194"));
startActivity(intent);
But what if?
public class MainActivity extends AppCompatActivity {
public static final String TARGET_ACTIVITY_DATA_KEY = "KEY1";
public static final String TARGET_ACTIVITY_MORE_DATA_KEY = "KEY2";
public static final String TARGET_ACTIVITY_EVEN_MORE_DATA_KEY = "KEY3";
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra(TARGET_ACTIVITY_DATA_KEY,"Luke Skywalker");
intent.putExtra(TARGET_ACTIVITY_MORE_DATA_KEY,"Darth Vader");
intent.putExtra(TARGET_ACTIVITY_EVEN_MORE_DATA_KEY,"Han Solo");
startActivity(intent);
}
But what if?
public class TargetActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_target);
Bundle extras = getIntent().getExtras();
String first = (String) extras.get(MainActivity.TARGET_ACTIVITY_DATA_KEY);
String second = extras.getString(MainActivity.TARGET_ACTIVITY_MORE_DATA_KEY);
int error = extras.getInt(MainActivity.TARGET_ACTIVITY_EVEN_MORE_DATA_KEY);
initViews(first,second,error);
}
What wrong?
- Non readable
- Mix of static variables
- Other activities should know what target expect
- Run-time error
Solution
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = TargetActivity
.createIntent(this, "Luke Skywalker", "Darth Vader", "Han Solo");
startActivity(intent);
}
}
Solution
public class TargetActivity extends AppCompatActivity {
public static final String TARGET_ACTIVITY_DATA_KEY = "KEY1";
public static final String TARGET_ACTIVITY_MORE_DATA_KEY = "KEY2";
public static final String TARGET_ACTIVITY_EVEN_MORE_DATA_KEY = "KEY3";
public static Intent createIntent(Context context,String first,String second,
String third){
Intent intent = new Intent(context, TargetActivity.class);
intent.putExtra(TARGET_ACTIVITY_DATA_KEY,first);
intent.putExtra(TARGET_ACTIVITY_MORE_DATA_KEY,second);
intent.putExtra(TARGET_ACTIVITY_EVEN_MORE_DATA_KEY,third);
return intent;
}
SharedPreferences
SettingsActivity
D
SharedPreferences
- Great thing to store persistent various.
- Not accessible by other apps*
- Used to save things between sessions
- Sometimes could be great communication tool (like intent) using
“onSharedPreferenceChangeListener”
MainActivity
public static final String TEXT_SHARED_PREF_KEY = "TEXT_SHARED_PREF_KEY";
public static final String SHARED_PREF_KEY = "KEY_FOR_SHARED_PREF";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button saveBtn = (Button) findViewById(R.id.btn_am_save_data);
Button restoreBtn = (Button) findViewById(R.id.btn_am_restore_data);
saveBtn.setOnClickListener(this);
restoreBtn.setOnClickListener(this);
}
MainActivity
@Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences(SHARED_PREF_KEY, MODE_PRIVATE);
EditText editText = (EditText) findViewById(R.id.et_am_text);
switch (v.getId()) {
case R.id.btn_am_save_data:
SharedPreferences.Editor editor = preferences.edit();
editor.putString(TEXT_SHARED_PREF_KEY, editText.getText().toString());
editor.apply();
finish();
break;
case R.id.btn_am_restore_data:
String text = preferences.getString(TEXT_SHARED_PREF_KEY,"");
editText.setText(text);
break;
}
And...
- Don’t forget that each commit() is I/O operation.
- use Apply() instead
Last Part:
Broadcast Receivers
E
Broadcast Receivers
Great guy :)
- Loose Coupling
- 1-to-n relationship
- The onReceive() method is always executed on the main thread
- You can notify components in your entire application, so the
communicating components do not have to "see" each other.
But...
- Marshaling data via intent really hard
- Register/Unregister it when you do not needed him (BaseActivity)
- Not build to transfer large objects
Receiver
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP =
"com.example.intent.action.PROGRESS_DOWNLOAD";
@Override
public void onReceive(Context context, Intent intent) {
TextView result = (TextView) findViewById(R.id.tv_am_progress);
String text = intent.getStringExtra(DownloadService.PROGRESS);
result.setText(text + "%");
}
}
Receiver
@Override
public void onClick(View v) {
Intent intent = new Intent(this, DownloadService.class);
startService(intent);
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
}
@Override
protected void onStop() {
unregisterReceiver(receiver);
super.onStop();
}
Receiver
<application
...
>
...
<receiver android:name=".MainActivity$ResponseReceiver"/>
</application>
Broadcast
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.ResponseReceiver.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PROGRESS, ""+i);
sendBroadcast(broadcastIntent);
*sendStickyBroadcast() - no longer available
Security hole!!!
Security Threat!!!
How to treat?
Use LocalBroadcastManager
Validate the intent that you got
Validate permissions
Android Toasts and Listeners

More Related Content

Viewers also liked

Session #7 rich and responsive layouts
Session #7  rich and responsive layoutsSession #7  rich and responsive layouts
Session #7 rich and responsive layoutsVitali Pekelis
 
Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adaptersVitali Pekelis
 
Session #5 content providers
Session #5  content providersSession #5  content providers
Session #5 content providersVitali Pekelis
 
Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your appVitali Pekelis
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragmentsVitali Pekelis
 
Android pro tips trilogy
Android  pro tips trilogyAndroid  pro tips trilogy
Android pro tips trilogyVitali Pekelis
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android projectVitali Pekelis
 
Android material design lecture #2
Android material design   lecture #2Android material design   lecture #2
Android material design lecture #2Vitali Pekelis
 
Android design lecture #1
Android design   lecture #1Android design   lecture #1
Android design lecture #1Vitali Pekelis
 

Viewers also liked (10)

Session #7 rich and responsive layouts
Session #7  rich and responsive layoutsSession #7  rich and responsive layouts
Session #7 rich and responsive layouts
 
Session #6 loaders and adapters
Session #6  loaders and adaptersSession #6  loaders and adapters
Session #6 loaders and adapters
 
Session #5 content providers
Session #5  content providersSession #5  content providers
Session #5 content providers
 
Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your app
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragments
 
Performance #1 memory
Performance #1   memoryPerformance #1   memory
Performance #1 memory
 
Android pro tips trilogy
Android  pro tips trilogyAndroid  pro tips trilogy
Android pro tips trilogy
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android project
 
Android material design lecture #2
Android material design   lecture #2Android material design   lecture #2
Android material design lecture #2
 
Android design lecture #1
Android design   lecture #1Android design   lecture #1
Android design lecture #1
 

Similar to Android Toasts and Listeners

Cucumber meets iPhone
Cucumber meets iPhoneCucumber meets iPhone
Cucumber meets iPhoneErin Dees
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intentPERKYTORIALS
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011sullis
 
iLabs Toolbox Javashare 2008
iLabs Toolbox Javashare 2008iLabs Toolbox Javashare 2008
iLabs Toolbox Javashare 2008rmzdotno
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2Dori Waldman
 
Android Framework
Android FrameworkAndroid Framework
Android FrameworkCodeAndroid
 
Android design patterns
Android design patternsAndroid design patterns
Android design patternsPlatty Soft
 
Android design patterns
Android design patternsAndroid design patterns
Android design patternsVitali Pekelis
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptxMugiiiReee
 
Get an Android tutorial for beginners
Get an Android tutorial for beginnersGet an Android tutorial for beginners
Get an Android tutorial for beginnersJavaTpoint.Com
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _courseDori Waldman
 
Basics of Android
Basics of Android Basics of Android
Basics of Android sabi_123
 
Functional Requirements Of System Requirements
Functional Requirements Of System RequirementsFunctional Requirements Of System Requirements
Functional Requirements Of System RequirementsLaura Arrigo
 
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docPalakjaiswal43
 

Similar to Android Toasts and Listeners (20)

Cucumber meets iPhone
Cucumber meets iPhoneCucumber meets iPhone
Cucumber meets iPhone
 
Android App development III
Android App development IIIAndroid App development III
Android App development III
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011
 
iLabs Toolbox Javashare 2008
iLabs Toolbox Javashare 2008iLabs Toolbox Javashare 2008
iLabs Toolbox Javashare 2008
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
 
Android Framework
Android FrameworkAndroid Framework
Android Framework
 
Activity & Shared Preference
Activity & Shared PreferenceActivity & Shared Preference
Activity & Shared Preference
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
Android design patterns
Android design patternsAndroid design patterns
Android design patterns
 
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx11.11.2020 - Unit 5-3  ACTIVITY, MENU AND SQLITE DATABASE.pptx
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
 
Get an Android tutorial for beginners
Get an Android tutorial for beginnersGet an Android tutorial for beginners
Get an Android tutorial for beginners
 
Android
AndroidAndroid
Android
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
 
Basics of Android
Basics of Android Basics of Android
Basics of Android
 
Android development first steps
Android development   first stepsAndroid development   first steps
Android development first steps
 
Functional Requirements Of System Requirements
Functional Requirements Of System RequirementsFunctional Requirements Of System Requirements
Functional Requirements Of System Requirements
 
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.docANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.doc
 
Android app development
Android app developmentAndroid app development
Android app development
 

More from Vitali Pekelis

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Vitali Pekelis
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Vitali Pekelis
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architectureVitali Pekelis
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & AnimationsVitali Pekelis
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networkingVitali Pekelis
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memoryVitali Pekelis
 
All the support you need. Support libs in Android
All the support you need. Support libs in AndroidAll the support you need. Support libs in Android
All the support you need. Support libs in AndroidVitali Pekelis
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practicesVitali Pekelis
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading Vitali Pekelis
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweetsVitali Pekelis
 
Lecture #4 c loaders and co.
Lecture #4 c   loaders and co.Lecture #4 c   loaders and co.
Lecture #4 c loaders and co.Vitali Pekelis
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providersVitali Pekelis
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perfVitali Pekelis
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3Vitali Pekelis
 

More from Vitali Pekelis (20)

Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940Droidkaigi2019thagikura 190208135940
Droidkaigi2019thagikura 190208135940
 
Droidkaigi 2019
Droidkaigi 2019Droidkaigi 2019
Droidkaigi 2019
 
Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019Google i o &amp; android q changes 2019
Google i o &amp; android q changes 2019
 
Android Q 2019
Android Q 2019Android Q 2019
Android Q 2019
 
Advanced #6 clean architecture
Advanced #6  clean architectureAdvanced #6  clean architecture
Advanced #6 clean architecture
 
Advanced #4 GPU & Animations
Advanced #4   GPU & AnimationsAdvanced #4   GPU & Animations
Advanced #4 GPU & Animations
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networking
 
Advanced #2 threading
Advanced #2   threadingAdvanced #2   threading
Advanced #2 threading
 
Advanced #1 cpu, memory
Advanced #1   cpu, memoryAdvanced #1   cpu, memory
Advanced #1 cpu, memory
 
All the support you need. Support libs in Android
All the support you need. Support libs in AndroidAll the support you need. Support libs in Android
All the support you need. Support libs in Android
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practices
 
Di &amp; dagger
Di &amp; daggerDi &amp; dagger
Di &amp; dagger
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading
 
Mobile ui fruit or delicious sweets
Mobile ui  fruit or delicious sweetsMobile ui  fruit or delicious sweets
Mobile ui fruit or delicious sweets
 
Lecture #4 c loaders and co.
Lecture #4 c   loaders and co.Lecture #4 c   loaders and co.
Lecture #4 c loaders and co.
 
Session #4 b content providers
Session #4 b  content providersSession #4 b  content providers
Session #4 b content providers
 
Advanced #2 - ui perf
 Advanced #2 - ui perf Advanced #2 - ui perf
Advanced #2 - ui perf
 
Android meetup
Android meetupAndroid meetup
Android meetup
 
Android design lecture #3
Android design   lecture #3Android design   lecture #3
Android design lecture #3
 
From newbie to ...
From newbie to ...From newbie to ...
From newbie to ...
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 

Android Toasts and Listeners

  • 1. Android Academy Session #3 Yonatan Levin Activities and Intents 3
  • 4.
  • 5. ~ 2000 members Largest Android Active Community
  • 6. Jonathan Yarkoni Android Developer & Advocate Ironsource Android Academy Staff Yonatan Levin Google Developer Expert & Android @ Gett Britt Barak Android Lead Figure8 Yossi Segev Android Developer Crave
  • 7. What Do We Do? ●Android Fundamentals ●Android UI / UX ●Community Hackathon ●Android Performance ●Mentors Program
  • 8. Online Lessons Important: Watch online lesson before the meetup! - Our course: “Developing Android Apps” goo.gl/u1pxZv - Optional: Nano Degree - Optional: “Android Basics” courses
  • 9. The Course Plan - Online lesson @ home! - Lecture @ Campus - Hands-on @ Campus - Questions @ Facebook
  • 11.
  • 12.
  • 15. What’s For Today? ● Listeners ● Toasts ● Intents, StartActivity, Navigation ● SharedPreferences
  • 16. I ❤ Today’s Lecture! In this lecture, besides the Android stuff, we will show-case 2 design patterns: Hidden Agenda for Today The Observer Pattern The Static Factory Method Pattern
  • 17. Design Patterns will be in Purple slides. Design patterns will get this background. If you don’t know design patterns, it’s never too late to learn.
  • 19. a CLASSic A Java Moment -
  • 20. OuterClass.InnerClass innerObject = outerObject.new InnerClass(); Consider this Crazy java codeline
  • 21. Nested Classes In Java, a class (or interface) can be declared inside another class. class A{ class B{ // ... } } Read more: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html Inside C, you can use A.B: class C{ A.B abMember; A.B doSomething(){ /* … */ } }
  • 22. Nested Classes There are 2 types of nested classes: class A{ // This one is called a static nested class. static class B{ // ... } // This one is called an inner class - because there’s no static. class B{ // ... } } Read more: https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
  • 23. Nested Classes - a Map Read more: https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html Nested Class Static Nested Class Inner Class Local class Anonymous Class Examples: ViewHolder AsyncTask Examples: Runnable OnClick
  • 24. OuterClass.InnerClass innerObject = outerObject.new InnerClass(); Consider this Crazy java codeline
  • 25. Our Starting Point in activity_main.xml: <Button android:text="Hooking to buttons" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="goToButtonsDemo" /> In MainActivity.java: public void goToButtonsDemo(View view) { Intent i = new Intent(this, ButtonsDemoActivity.class); startActivity(i); }
  • 26. Handling Events 3 ways to listen(er)s
  • 27. Way #1: android:onClick=”...” in xml In activity_buttons_demo.xml declare the button with an OnClick: <Button android:text="Red +" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:onClick="increaseRed" android:background="@color/lightred" /> In ButtonsDemoActivity.java, implement the method that will be called public void increaseRed(View view) { // ... }
  • 28. Way #2: Inline OnClickListener In the Activity’s onCreate method, grab the buttons and set their OnClickListener with an inline implementation @Override protected void onCreate(Bundle savedInstanceState) { // ... Button increaseGreen = (Button)findViewById(R.id.buttonsdemo_incGreen); increaseGreen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ... } }); }
  • 29. Way #3: Single OnClickListener (1) Make the activity implement View.OnClickListener: public class ButtonsDemoActivity extends ActionBarActivity implements View.OnClickListener (2) In OnCreate, set the button’s listener to the activity (with this): @Override protected void onCreate(Bundle savedInstanceState) { // … Button decreaseRed = (Button)findViewById(R.id.buttonsdemo_decRed); decreaseRed.setOnClickListener(this); }
  • 30. Way #3: Single OnClickListener (3) Implement the interface, use a switch to tell which button view was clicked: @Override public void onClick(View v) { switch (v.getId()){ case R.id.buttonsdemo_decRed: red = calcNewValue(red, -1); break; case R.id.buttonsdemo_decGreen: green = calcNewValue(green, -1); break; case R.id.buttonsdemo_decBlue: blue = calcNewValue(blue, -1); break; } refreshDisplay();
  • 31. Demo: The Color Mixer 1 Button: Way #1 2 Buttons: Way #2 3 Buttons: Way #3
  • 32. Not really 3 ways... In fact, there’s only one way to have a button do something: Set a View.OnClickListener. Way #1 does this implicitly, and ways 2,3 does this explicitly.
  • 33. What is a listener? Listener: an interface that contains a single callback method. When the user interacts with the UI, the Views trigger a call to the listener (if it’s not null) and calls the callback. As long as the view and the listener agrees on the contract between them (~ The method’s signature), the view doesn’t care what the implementation is. This is a great example of the Observer design pattern. Source: http://developer.android.com/guide/topics/ui/ui-events.html#EventListeners
  • 34. The Observer Design Pattern A Behavioral design pattern, commonly used in UI (but not only). Read a lot more: https://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Observer View.OnClickListener View Your Listener
  • 35. How does xml onClick (way #1) work When you use the xml’s onClick way, the View uses a View.DeclaredOnClickListener, It uses reflection (which is slow on android), but It’s Lazy and Cached, and is not validated at Compile-Time. Since android is Open-Source, check out the implementation at the link below. https://github.com/android/platform_frameworks_base/blob/master/core/java/android/view/View.java Line 4429
  • 36. Which is better? Way #1: onClick=”...” → DeclaredOnClickListener Way #2: inline listener implementation Way #3: activity interface implementation http://stackoverflow.com/questions/21319996/android-onclick-in-xml-vs-onclicklistener Pros: Clean code, no findViewById at all Cons: Reflection, No Compile-Time validation, API Level ≥ 4, not readable Pros: Readable code Cons: +1 class, +1 method, ~500 bytes, +Boilerplate code, if you have a lot of clicks becomes mess Pros: No object allocations Cons: Felix: The horrible switch (over view.getId())
  • 37. What other listeners are available? Read more: http://developer.android.com/guide/topics/ui/ui-events.html Event Handler onClick View.OnClickListener onLongClick View.OnLongClickListener onFocusChange View.OnFocusChangeListener onKey View.OnKeyListener onTouch View.OnTouchListener onCreateContextMenu View.OnCreateContextMenuListener AdapterView.OnItemClickListener
  • 38. Non-void Listeners Some flows requires listeners to tell when they take care of the event. These listeners return a boolean: true if the event is consumed, or false if it isn’t. onTouchListener is a good example.
  • 39. OnClick || OnTouch? OnTouch gets called on any change in the touch detection, and contains touch data. The MotionEvent is passed to the root view, and it travels until it finds an OnTouchListener that would handle it. Some may react to the event without consuming it - common practice for when using Gesture Detectors. For “Everyday tapping” - You usually should go with onClick. Read More: http://codetheory.in/understanding-android-input-touch-events/
  • 40. Take Aways - Listeners 1.UI Interaction is implemented with Listeners. 2.Some listeners returns a boolean value to indicate handling. 3.OnTouch is really important, and in most cases, you won’t need it.
  • 41. And the Static Factory Method pattern Toasts B
  • 42. Toasts provides simple feedback about an operation in a small popup. The current activity remains visible and interactive - But the toast itself is not interactive. Toast disappear after a short time. http://developer.android.com/guide/topics/ui/notifiers/toasts.html
  • 43. Make a Toast Toast.makeText(this,"I'm your father,Luke!",Toast.LENGTH_LONG) .show();
  • 45. Static Factory Method ●The best ways to create an object. ●Have a name ●Can cache and not always create new class ●They return an object ●Reduce the verbosity of creating parameterized type instances Read more: http://www.informit.com/articles/article.aspx?p=1216151
  • 46. Static Factory Method public static Toast makeText(Context context, CharSequence text, @Duration int duration) { Toast result = new Toast(context); LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null); TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message); tv.setText(text); result.mNextView = v; result.mDuration = duration; return result; } Read more:
  • 47. Most important thing about Toasts: show()
  • 48. Not in course: Snackbars Defined in the Material Design spec, SnackBars also allow user interaction - and also work great with FABs - Both are out-of-scope from our course. http://developer.android.com/reference/android/support/design/widget/Snackbar.html
  • 49. If you need user interaction, you can use a notification (which we’ll see in Session #6) and if you really need a custom toast design, you can - but it’s not covered here. Also not talking about...
  • 50. - It lets newly created objects understand what has been going on. - Global information about an application environment - Creating New objects: Creating new views, adapters, listeners: TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...); - Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences: context.getSystemService(LAYOUT_INFLATER_SERVICE); getApplicationContext().getSharedPreferences(*name*, *mode*); - Accessing Components Implicitly: Regarding content providers, broadcasts, intent: getApplicationContext().getContentResolver().query(uri, ...); Context - #1 reason of memory leaks - Further reads: https://possiblemobile.com/2013/06/context/
  • 51. View svButton = findViewById(R.id.sv_button); svButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setStaticView(); } });
  • 52. public static View view; void setStaticView() { view = findViewById(R.id.sv_button); }
  • 53.
  • 54. and also a bit about Navigation Intents and StartActivity C
  • 55. Intents messaging object you can to request an action from another app component. Main Use-cases: - Starting an activity - Broadcasting a message - Starting a service (wait for Session 6) http://developer.android.com/guide/components/intents-filters.html
  • 56. Intent Types Explicit Intent - have a ComponentName - so Android knows exactly what to call. Implicit Intent, doesn’t have a ComponentName - so Android uses Intent Filters to know what to do.
  • 57. used for Explicit Intents used for Implicit Intents used to tell things to the recipient used to tell things to the messenger Intents have... Component Name Action Data (and Type) Category Extras Flags
  • 58. Intent Filters Intent filters are used to advertise what intents your app can handle. We’ve already seen MainActivity’s intent filter in Session #1. Read more: http://developer.android.com/guide/components/intents-filters.html#Receiving
  • 59. Explicitly Intent intent = new Intent(this, TargetActivity.class); startActivity(intent); or Intent intent = new Intent(getApplicationContext(), TargetActivity.class); getApplicationContext().startActivity(intent);
  • 60. Implicitly Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:37.7749,-122.4194")); startActivity(intent);
  • 61. But what if? public class MainActivity extends AppCompatActivity { public static final String TARGET_ACTIVITY_DATA_KEY = "KEY1"; public static final String TARGET_ACTIVITY_MORE_DATA_KEY = "KEY2"; public static final String TARGET_ACTIVITY_EVEN_MORE_DATA_KEY = "KEY3"; @Override protected void onCreate(Bundle savedInstanceState) { Intent intent = new Intent(this, TargetActivity.class); intent.putExtra(TARGET_ACTIVITY_DATA_KEY,"Luke Skywalker"); intent.putExtra(TARGET_ACTIVITY_MORE_DATA_KEY,"Darth Vader"); intent.putExtra(TARGET_ACTIVITY_EVEN_MORE_DATA_KEY,"Han Solo"); startActivity(intent); }
  • 62. But what if? public class TargetActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_target); Bundle extras = getIntent().getExtras(); String first = (String) extras.get(MainActivity.TARGET_ACTIVITY_DATA_KEY); String second = extras.getString(MainActivity.TARGET_ACTIVITY_MORE_DATA_KEY); int error = extras.getInt(MainActivity.TARGET_ACTIVITY_EVEN_MORE_DATA_KEY); initViews(first,second,error); }
  • 63. What wrong? - Non readable - Mix of static variables - Other activities should know what target expect - Run-time error
  • 64. Solution public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { Intent intent = TargetActivity .createIntent(this, "Luke Skywalker", "Darth Vader", "Han Solo"); startActivity(intent); } }
  • 65. Solution public class TargetActivity extends AppCompatActivity { public static final String TARGET_ACTIVITY_DATA_KEY = "KEY1"; public static final String TARGET_ACTIVITY_MORE_DATA_KEY = "KEY2"; public static final String TARGET_ACTIVITY_EVEN_MORE_DATA_KEY = "KEY3"; public static Intent createIntent(Context context,String first,String second, String third){ Intent intent = new Intent(context, TargetActivity.class); intent.putExtra(TARGET_ACTIVITY_DATA_KEY,first); intent.putExtra(TARGET_ACTIVITY_MORE_DATA_KEY,second); intent.putExtra(TARGET_ACTIVITY_EVEN_MORE_DATA_KEY,third); return intent; }
  • 67. SharedPreferences - Great thing to store persistent various. - Not accessible by other apps* - Used to save things between sessions - Sometimes could be great communication tool (like intent) using “onSharedPreferenceChangeListener”
  • 68. MainActivity public static final String TEXT_SHARED_PREF_KEY = "TEXT_SHARED_PREF_KEY"; public static final String SHARED_PREF_KEY = "KEY_FOR_SHARED_PREF"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button saveBtn = (Button) findViewById(R.id.btn_am_save_data); Button restoreBtn = (Button) findViewById(R.id.btn_am_restore_data); saveBtn.setOnClickListener(this); restoreBtn.setOnClickListener(this); }
  • 69. MainActivity @Override public void onClick(View v) { SharedPreferences preferences = getSharedPreferences(SHARED_PREF_KEY, MODE_PRIVATE); EditText editText = (EditText) findViewById(R.id.et_am_text); switch (v.getId()) { case R.id.btn_am_save_data: SharedPreferences.Editor editor = preferences.edit(); editor.putString(TEXT_SHARED_PREF_KEY, editText.getText().toString()); editor.apply(); finish(); break; case R.id.btn_am_restore_data: String text = preferences.getString(TEXT_SHARED_PREF_KEY,""); editText.setText(text); break; }
  • 70. And... - Don’t forget that each commit() is I/O operation. - use Apply() instead
  • 72. Broadcast Receivers Great guy :) - Loose Coupling - 1-to-n relationship - The onReceive() method is always executed on the main thread - You can notify components in your entire application, so the communicating components do not have to "see" each other.
  • 73.
  • 74. But... - Marshaling data via intent really hard - Register/Unregister it when you do not needed him (BaseActivity) - Not build to transfer large objects
  • 75. Receiver public class ResponseReceiver extends BroadcastReceiver { public static final String ACTION_RESP = "com.example.intent.action.PROGRESS_DOWNLOAD"; @Override public void onReceive(Context context, Intent intent) { TextView result = (TextView) findViewById(R.id.tv_am_progress); String text = intent.getStringExtra(DownloadService.PROGRESS); result.setText(text + "%"); } }
  • 76. Receiver @Override public void onClick(View v) { Intent intent = new Intent(this, DownloadService.class); startService(intent); IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new ResponseReceiver(); registerReceiver(receiver, filter); } @Override protected void onStop() { unregisterReceiver(receiver); super.onStop(); }
  • 78. Broadcast Intent broadcastIntent = new Intent(); broadcastIntent.setAction(MainActivity.ResponseReceiver.ACTION_RESP); broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); broadcastIntent.putExtra(PROGRESS, ""+i); sendBroadcast(broadcastIntent); *sendStickyBroadcast() - no longer available
  • 80. How to treat? Use LocalBroadcastManager Validate the intent that you got Validate permissions