SlideShare a Scribd company logo
Communication Between
Android Application
Components
Aleksandar Ilić
March 20, 2014
@aleksandar_ilic
linkedin.com/in/ailic
How to be flexible?
Encapsulate atomic portions
of application’s user interface
or behavior.
Fragments
What is a Fragment?
res/layout/contacts_activity.xml
<FrameLayout>
<fragment android:name="rs.pstech.android.ContactsList“
android:id="@+id/contacts_list"
android:layout_width="match_parent"
android:layout_height="match_parent“ />
</FrameLayout>
res/layout-sw800dp/contacts_activity.xml
<LinearLayout>
<fragment android:name="rs.pstech.android.ContactsList“
android:id="@+id/contacts_list"
android:layout_weight="0.30"
android:layout_width="0dp"
android:layout_height="match_parent“ />
<fragment android:name="rs.pstech.android.ContactDetail“
android:id="@+id/contact_details"
android:layout_weight="0.70"
android:layout_width="0dp"
android:layout_height="match_parent“ />
</LinearLayout>
Fragments creation
Fragments creation
public class ContactsList extends ListFragment {
/** Key to find the data uri in a bundle. */
private static String ARG_DATA_URI = "ArgDataUri";
private Uri mDataUri;
public ContactsList() {
// Do NOT use constructors
}
public static ContactsList newInstance(Uri uri) {
Bundle args = new Bundle();
args.putParcelable(ARG_DATA_URI, uri);
ContactsList fragment = new ContactsList();
fragment.setArgments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDataUri = getArguments().getParcelable(ARG_DATA_URI);
}
}
Fragments creation
Communication with activities
public class ContactsList extends ListFragment
implements AdapterView.OnItemClickListener {
// Container Activity must implement this interface
public interface OnContactsActionListener {
void onViewContactAction(Uri contactUri);
}
private OnContactsActionListener mCallback;
@Override
public void onAttach(Activity activity) {
super.onAttach(context);
try {
mCallback = (OnContactsActionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnContactsActionListener");
}
}
}
Communication with activities
public class ContactsActivity extends FragmentActivity
implements OnContactsActionListener {
:::
@Override
public void onViewContactAction(Uri contactUri) {
ContactDetail contactDetailFragment = (ContactDetail)
getFragmentManager().findFragmentById(R.id.contact_detail);
if (contactDetailFragment != null) {
// If contact detail is available we are in two-pane layout
// Update contact detail’s data
contactDetailsFragment.loadData(contactUri);
} else {
// Otherwise we are in one-pane layout
// Start activity to view the contact
startActivity(new Intent(Intent.ACTION_VIEW, contactUri));
}
}
}
Communication with activities
Communication with fragments
Communication with fragments
public class BackupAccountDialog extends DialogFragment {
public interface OnAccountSelectedListener {
void onAccountSelected(Account account);
}
public OnAccountSelectedListener mCallback;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (getTargetFragment() instanceof OnAccountSelectedListener) {
mCallback = (OnAccountSelectedListener) getTargetFragment();
} else if (getParentFragment() instanceof OnAccountSelectedListener) {
mCallback = (OnAccountSelectedListener) getParentFragment();
} else {
if (activity instanceof OnAccountSelectedListener) {
mCallback = (OnAccountSelectedListener) activity;
} else {
throw new RuntimeExcpetion("What now?");
}
}
}
}
Communication with fragments
public class ContactsList extends Fragment
implements OnAccountSelectedListener {
:::
private void showSelectBackupAccount() {
BackupAccountDialog dialog = BackupAccountDialog.newInstance();
dialog.setTargetFragment(this, 0);
dialog.show(getFragmentManager(), "selectBackupAccountDialog");
}
@Override
public void onAccountSelected(Account account) {
// Do something when account is selected
}
}
Communication with fragments
How to be smooth?
Offload long-running operations
from Main UI thread.
Threads
Main Thread
• In charge of dispatching events (incl. drawing events)
to user interface widgets.
Main Thread
• In charge of dispatching events (incl. drawing events)
to user interface widgets.
• All components that run in the same process are
instantiated in the Main (UI) thread.
Main Thread
• In charge of dispatching events (incl. drawing events)
to user interface widgets.
• All components that run in the same process are
instantiated in the Main (UI) thread.
• Android UI toolkit (components from the android.widget
and android.view packages) is not thread-safe.
Main Thread Rules
Do not block the Main thread.
Do not access the Android toolkit
from outside the Main thread.
Accessing Main Thread
• Activity.runOnUiThread(Runnable)
• View.post(Runnable)
• View.postDelayed(Runnable, long)
public void onClick(View v) {
@Override
new Thread(new Runnable() {
public void run() {
final Bitmap bitmap = downloadImage("http://pstech.rs/logo.png");
mImageView.post(new Runnable() {
@Override
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
}).start();
}
Worker Thread - Example
Handlers
What is an Async Task?
• Designed to be helper class around Thread and Handler.
What is an Async Task?
• Designed to be helper class around Thread and Handler.
• Ideally to be used for short operations (a few seconds at
the most).
What is an Async Task?
• Designed to be helper class around Thread and Handler.
• Ideally to be used for short operations (a few seconds at
the most).
• Defined by 3 generic types: Params, Progress and
Result and 4 steps: onPreExecute, doInBackground,
onProgressUpdate and onPostExecute.
Async Task – Handling configuration changes
Async Task – Handling configuration changes
Services
What is not a Service?
Why Service?
• A service can run in the background to perform work
even while the user is in a different application.
Why Service?
• A service can run in the background to perform work
even while the user is in a different application.
• A service can allow other components to bind to it, in
order to interact with it and perform interprocess
communication.
Intent Service
public class ContactEditorActivity extends FragmentActivity {
:::
private void saveContact() {
Intent saveAction = ContactSaveService.createSaveContactIntent(…);
startService(saveAction);
}
:::
}
IntentService usage
public class ContactSaveService extends IntentService {
private static final String ACTION_SAVE_CONTACT = "saveContact";
private static final String ACTION_DELETE_CONTACT = "deleteContact";
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_SAVE_CONTACT.equals(action)) {
doSaveContact(intent);
} else if (ACTION_DELETE_CONTACT.equals(action) {
doDeleteContact(intent);
}
}
public static Intent createSaveContactIntent(Context context, …) {
Intent serviceIntent = new Intent(context, ContactSaveService.class);
serviceIntent.putExtra(…, …);
return serviceIntent;
}
:::
}
IntentService creation
What about callbacks?
What about callbacks?
Result Receiver
Broadcast Receiver
What is a Result Receiver?
• Generic interface for receiving a callback result from
someone.
public class ContactEditorActivity extends FragmentActivity {
:::
private void saveContact() {
Intent saveAction = ContactSaveService.createSaveContactIntent(
getActivity(), mOnSaveContactCallback, …);
startService(saveAction);
}
ResultReceiver mOnSaveContactCallback = new ResultReceiver(mHandler) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Do something when contact is saved.
// On a thread associated with given mHandler.
}
};
:::
}
Result Receiver – Client side
public class ContactSaveService extends IntentService {
private static final String EXTRA_CALLBACK = "extraCallback";
public static Intent createSaveContactIntent(Context context,
ResultReceiver resultReceiver, …) {
Intent serviceIntent = new Intent(context, ContactSaveService.class);
serviceIntent.putExtra(EXTRA_CALLBACK, resultReceiver);
serviceIntent.putExtra(…, …);
return serviceIntent;
}
private void doSaveContact(Intent intent) {
:::
int resultCode = 0;
Bundle resultData = new Bundle(); // Result for the listener
ResultReceiver callback = intent.getParcelable(EXTRA_CALLBACK);
callback.send(resultCode, resultData);
}
}
Result Receiver – Service side
What is a Broadcast Receiver?
sendBroadcast() onReceive()
Broadcast Receiver - Lifecycles
Local Broadcast Manager
• Helper to register for and send broadcasts of Intents to
local objects within your process.
Local Broadcast Manager
• Helper to register for and send broadcasts of Intents to
local objects within your process.
Private Secure
Efficient
Broadcast Receiver – Client side
public class ContactEditorActivity extends FragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
LocalBroadcastManager mLocalBroadcastManager =
LocalBroadcastManager.getInstance(this);
IntentFilter mContactSavedIntentFilter =
new IntentFilter(Constants.BROADCAST_CONTACT_SAVED);
mLocalBrodcastManager.registerReceiver(
mContactSavedReceiver, mContactSavedIntentFilter);
}
protected void onDestroy() {
mLocalBrodcastManager.unregisterReceiver(mContactSavedReceiver);
}
BroadcastReceiver mContactSavedReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Do something when contact is saved.
}
};
}
Broadcast Receiver – Service side
public class ContactSaveService extends IntentService {
public static Intent createSaveContactIntent(Context context, …) {
Intent serviceIntent = new Intent(context, ContactSaveService.class);
serviceIntent.putExtra(…, …);
return serviceIntent;
}
private void doSaveContact(Intent intent) {
:::
Intent localIntent = new Intent(Constants.BROADCAST_CONTACT_SAVED);
localIntent.putExtra(…, …);
// Broadcasts the Intent to receivers in this app.
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
}
How to be up to date?
Loaders are your friends when
performing asynchronous
loading of data.
Loaders
What are Loaders?
API
LoaderManager LoaderManager.LoaderCallbacks
Loader AsyncTaskLoader CursorLoader
Why Loaders?
• They are available to every Activity and Fragment.
Why Loaders?
• They are available to every Activity and Fragment.
• They provide asynchronous loading of data.
Why Loaders?
• They are available to every Activity and Fragment.
• They provide asynchronous loading of data.
• They monitor the source of their data and deliver new
results when the content changes.
Why Loaders?
• They are available to every Activity and Fragment.
• They provide asynchronous loading of data.
• They monitor the source of their data and deliver new
results when the content changes.
• They automatically reconnect to the last loader's cursor
when being recreated after a configuration change.
Thus, they don't need to re-query their data.
Using Cursor Loader
public class ContactsList extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
:::
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Initializes the loader. It will use the existing one or
// create and start a new one.
getLoaderManager().initLoader(ID, null /*bundle*/, this /*callbacks*/);
}
private void setDataUri(Uri dataUri) {
mDataUri = dataUri; // Assuming they are not equal
getLoaderManager().restartLoader(ID, null, this);
}
:::
Using Cursor Loader
:::
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), mDataUri, CONTACTS_PROJECITON,
null /*selection*/, null /*selArgs*/, Contacts.DISPLAY_NAME);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. The framework will close the old cursor.
mAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// Last cursor is about to be closed. We have to stop using it.
mAdapter.swapCursor(null);
}
}
• Volite Javu?
• Fokusirani ste na visok kvalitet
koda i optimizaciju performansi?
• Zainteresovani ste za prelazak
na Mobile razvoj?
bit.ly/Java2AndroidJava2Android
Thank You!
@aleksandar_ilic
linkedin.com/in/ailic
ailic89@gmail.com

More Related Content

What's hot

Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity Container
Mindfire Solutions
 
Vaadin 8 with Spring Frameworks AutoConfiguration
Vaadin 8 with Spring Frameworks AutoConfigurationVaadin 8 with Spring Frameworks AutoConfiguration
Vaadin 8 with Spring Frameworks AutoConfiguration
Peter Lehto
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
Dmitry Buzdin
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
Naga Muruga
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
MongoDB
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
Knoldus Inc.
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
Micha Kops
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
Peter Lehto
 
Mockito junit
Mockito junitMockito junit
Mockito junit
Santiago Plascencia
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
PhilWinstanley
 
Android ax app wcf
Android ax app wcfAndroid ax app wcf
Android ax app wcf
Aravindharamanan S
 
Android+ax+app+wcf
Android+ax+app+wcfAndroid+ax+app+wcf
Android+ax+app+wcf
Aravindharamanan S
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
Google Guice
Google GuiceGoogle Guice
Google Guice
Andriy Andrunevchyn
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
ellentuck
 
Knot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meetKnot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meet
Tomasz Michalak
 
Techlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinTechlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with Vaadin
Peter Lehto
 

What's hot (17)

Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity Container
 
Vaadin 8 with Spring Frameworks AutoConfiguration
Vaadin 8 with Spring Frameworks AutoConfigurationVaadin 8 with Spring Frameworks AutoConfiguration
Vaadin 8 with Spring Frameworks AutoConfiguration
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
Mockito junit
Mockito junitMockito junit
Mockito junit
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
 
Android ax app wcf
Android ax app wcfAndroid ax app wcf
Android ax app wcf
 
Android+ax+app+wcf
Android+ax+app+wcfAndroid+ax+app+wcf
Android+ax+app+wcf
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
Google Guice
Google GuiceGoogle Guice
Google Guice
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-cas
 
Knot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meetKnot.x: when Vert.x and RxJava meet
Knot.x: when Vert.x and RxJava meet
 
Techlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinTechlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with Vaadin
 

Similar to Java Svet - Communication Between Android App Components

Android best practices
Android best practicesAndroid best practices
Android best practices
Jose Manuel Ortega Candel
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
Joshua Long
 
Android101
Android101Android101
Android101
David Marques
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhoneMobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mohammad Shaker
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
Nataliya Patsovska
 
Working with data using Azure Functions.pdf
Working with data using Azure Functions.pdfWorking with data using Azure Functions.pdf
Working with data using Azure Functions.pdf
Stephanie Locke
 
Android app development basics
Android app development basicsAndroid app development basics
Android app development basics
Anton Narusberg
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
Monir Zzaman
 
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
Michael Bakogiannis
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
Alexis Hassler
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
Utkarsh Mankad
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
jason hu 金良胡
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
jason hu 金良胡
 

Similar to Java Svet - Communication Between Android App Components (20)

Android best practices
Android best practicesAndroid best practices
Android best practices
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
Android101
Android101Android101
Android101
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Mobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhoneMobile Software Engineering Crash Course - C06 WindowsPhone
Mobile Software Engineering Crash Course - C06 WindowsPhone
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Working with data using Azure Functions.pdf
Working with data using Azure Functions.pdfWorking with data using Azure Functions.pdf
Working with data using Azure Functions.pdf
 
Android app development basics
Android app development basicsAndroid app development basics
Android app development basics
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter LehtoJavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
JavaCro'14 - Building interactive web applications with Vaadin – Peter Lehto
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 
Ext Js Events
Ext Js EventsExt Js Events
Ext Js Events
 

Recently uploaded

Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
FODUU
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 

Recently uploaded (20)

Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 

Java Svet - Communication Between Android App Components

  • 1. Communication Between Android Application Components Aleksandar Ilić March 20, 2014 @aleksandar_ilic linkedin.com/in/ailic
  • 2. How to be flexible? Encapsulate atomic portions of application’s user interface or behavior.
  • 4. What is a Fragment?
  • 5. res/layout/contacts_activity.xml <FrameLayout> <fragment android:name="rs.pstech.android.ContactsList“ android:id="@+id/contacts_list" android:layout_width="match_parent" android:layout_height="match_parent“ /> </FrameLayout> res/layout-sw800dp/contacts_activity.xml <LinearLayout> <fragment android:name="rs.pstech.android.ContactsList“ android:id="@+id/contacts_list" android:layout_weight="0.30" android:layout_width="0dp" android:layout_height="match_parent“ /> <fragment android:name="rs.pstech.android.ContactDetail“ android:id="@+id/contact_details" android:layout_weight="0.70" android:layout_width="0dp" android:layout_height="match_parent“ /> </LinearLayout> Fragments creation
  • 7. public class ContactsList extends ListFragment { /** Key to find the data uri in a bundle. */ private static String ARG_DATA_URI = "ArgDataUri"; private Uri mDataUri; public ContactsList() { // Do NOT use constructors } public static ContactsList newInstance(Uri uri) { Bundle args = new Bundle(); args.putParcelable(ARG_DATA_URI, uri); ContactsList fragment = new ContactsList(); fragment.setArgments(args); return fragment; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDataUri = getArguments().getParcelable(ARG_DATA_URI); } } Fragments creation
  • 9. public class ContactsList extends ListFragment implements AdapterView.OnItemClickListener { // Container Activity must implement this interface public interface OnContactsActionListener { void onViewContactAction(Uri contactUri); } private OnContactsActionListener mCallback; @Override public void onAttach(Activity activity) { super.onAttach(context); try { mCallback = (OnContactsActionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnContactsActionListener"); } } } Communication with activities
  • 10. public class ContactsActivity extends FragmentActivity implements OnContactsActionListener { ::: @Override public void onViewContactAction(Uri contactUri) { ContactDetail contactDetailFragment = (ContactDetail) getFragmentManager().findFragmentById(R.id.contact_detail); if (contactDetailFragment != null) { // If contact detail is available we are in two-pane layout // Update contact detail’s data contactDetailsFragment.loadData(contactUri); } else { // Otherwise we are in one-pane layout // Start activity to view the contact startActivity(new Intent(Intent.ACTION_VIEW, contactUri)); } } } Communication with activities
  • 13. public class BackupAccountDialog extends DialogFragment { public interface OnAccountSelectedListener { void onAccountSelected(Account account); } public OnAccountSelectedListener mCallback; @Override public void onAttach(Activity activity) { super.onAttach(activity); if (getTargetFragment() instanceof OnAccountSelectedListener) { mCallback = (OnAccountSelectedListener) getTargetFragment(); } else if (getParentFragment() instanceof OnAccountSelectedListener) { mCallback = (OnAccountSelectedListener) getParentFragment(); } else { if (activity instanceof OnAccountSelectedListener) { mCallback = (OnAccountSelectedListener) activity; } else { throw new RuntimeExcpetion("What now?"); } } } } Communication with fragments
  • 14. public class ContactsList extends Fragment implements OnAccountSelectedListener { ::: private void showSelectBackupAccount() { BackupAccountDialog dialog = BackupAccountDialog.newInstance(); dialog.setTargetFragment(this, 0); dialog.show(getFragmentManager(), "selectBackupAccountDialog"); } @Override public void onAccountSelected(Account account) { // Do something when account is selected } } Communication with fragments
  • 15. How to be smooth? Offload long-running operations from Main UI thread.
  • 17. Main Thread • In charge of dispatching events (incl. drawing events) to user interface widgets.
  • 18. Main Thread • In charge of dispatching events (incl. drawing events) to user interface widgets. • All components that run in the same process are instantiated in the Main (UI) thread.
  • 19. Main Thread • In charge of dispatching events (incl. drawing events) to user interface widgets. • All components that run in the same process are instantiated in the Main (UI) thread. • Android UI toolkit (components from the android.widget and android.view packages) is not thread-safe.
  • 20. Main Thread Rules Do not block the Main thread. Do not access the Android toolkit from outside the Main thread.
  • 21. Accessing Main Thread • Activity.runOnUiThread(Runnable) • View.post(Runnable) • View.postDelayed(Runnable, long)
  • 22. public void onClick(View v) { @Override new Thread(new Runnable() { public void run() { final Bitmap bitmap = downloadImage("http://pstech.rs/logo.png"); mImageView.post(new Runnable() { @Override public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); } Worker Thread - Example
  • 24. What is an Async Task? • Designed to be helper class around Thread and Handler.
  • 25. What is an Async Task? • Designed to be helper class around Thread and Handler. • Ideally to be used for short operations (a few seconds at the most).
  • 26. What is an Async Task? • Designed to be helper class around Thread and Handler. • Ideally to be used for short operations (a few seconds at the most). • Defined by 3 generic types: Params, Progress and Result and 4 steps: onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
  • 27. Async Task – Handling configuration changes
  • 28. Async Task – Handling configuration changes
  • 30. What is not a Service?
  • 31. Why Service? • A service can run in the background to perform work even while the user is in a different application.
  • 32. Why Service? • A service can run in the background to perform work even while the user is in a different application. • A service can allow other components to bind to it, in order to interact with it and perform interprocess communication.
  • 34. public class ContactEditorActivity extends FragmentActivity { ::: private void saveContact() { Intent saveAction = ContactSaveService.createSaveContactIntent(…); startService(saveAction); } ::: } IntentService usage
  • 35. public class ContactSaveService extends IntentService { private static final String ACTION_SAVE_CONTACT = "saveContact"; private static final String ACTION_DELETE_CONTACT = "deleteContact"; @Override protected void onHandleIntent(Intent intent) { String action = intent.getAction(); if (ACTION_SAVE_CONTACT.equals(action)) { doSaveContact(intent); } else if (ACTION_DELETE_CONTACT.equals(action) { doDeleteContact(intent); } } public static Intent createSaveContactIntent(Context context, …) { Intent serviceIntent = new Intent(context, ContactSaveService.class); serviceIntent.putExtra(…, …); return serviceIntent; } ::: } IntentService creation
  • 37. What about callbacks? Result Receiver Broadcast Receiver
  • 38. What is a Result Receiver? • Generic interface for receiving a callback result from someone.
  • 39. public class ContactEditorActivity extends FragmentActivity { ::: private void saveContact() { Intent saveAction = ContactSaveService.createSaveContactIntent( getActivity(), mOnSaveContactCallback, …); startService(saveAction); } ResultReceiver mOnSaveContactCallback = new ResultReceiver(mHandler) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { // Do something when contact is saved. // On a thread associated with given mHandler. } }; ::: } Result Receiver – Client side
  • 40. public class ContactSaveService extends IntentService { private static final String EXTRA_CALLBACK = "extraCallback"; public static Intent createSaveContactIntent(Context context, ResultReceiver resultReceiver, …) { Intent serviceIntent = new Intent(context, ContactSaveService.class); serviceIntent.putExtra(EXTRA_CALLBACK, resultReceiver); serviceIntent.putExtra(…, …); return serviceIntent; } private void doSaveContact(Intent intent) { ::: int resultCode = 0; Bundle resultData = new Bundle(); // Result for the listener ResultReceiver callback = intent.getParcelable(EXTRA_CALLBACK); callback.send(resultCode, resultData); } } Result Receiver – Service side
  • 41. What is a Broadcast Receiver? sendBroadcast() onReceive()
  • 42. Broadcast Receiver - Lifecycles
  • 43. Local Broadcast Manager • Helper to register for and send broadcasts of Intents to local objects within your process.
  • 44. Local Broadcast Manager • Helper to register for and send broadcasts of Intents to local objects within your process. Private Secure Efficient
  • 45. Broadcast Receiver – Client side public class ContactEditorActivity extends FragmentActivity { protected void onCreate(Bundle savedInstanceState) { LocalBroadcastManager mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); IntentFilter mContactSavedIntentFilter = new IntentFilter(Constants.BROADCAST_CONTACT_SAVED); mLocalBrodcastManager.registerReceiver( mContactSavedReceiver, mContactSavedIntentFilter); } protected void onDestroy() { mLocalBrodcastManager.unregisterReceiver(mContactSavedReceiver); } BroadcastReceiver mContactSavedReciver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Do something when contact is saved. } }; }
  • 46. Broadcast Receiver – Service side public class ContactSaveService extends IntentService { public static Intent createSaveContactIntent(Context context, …) { Intent serviceIntent = new Intent(context, ContactSaveService.class); serviceIntent.putExtra(…, …); return serviceIntent; } private void doSaveContact(Intent intent) { ::: Intent localIntent = new Intent(Constants.BROADCAST_CONTACT_SAVED); localIntent.putExtra(…, …); // Broadcasts the Intent to receivers in this app. LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent); } }
  • 47. How to be up to date? Loaders are your friends when performing asynchronous loading of data.
  • 49. What are Loaders? API LoaderManager LoaderManager.LoaderCallbacks Loader AsyncTaskLoader CursorLoader
  • 50. Why Loaders? • They are available to every Activity and Fragment.
  • 51. Why Loaders? • They are available to every Activity and Fragment. • They provide asynchronous loading of data.
  • 52. Why Loaders? • They are available to every Activity and Fragment. • They provide asynchronous loading of data. • They monitor the source of their data and deliver new results when the content changes.
  • 53. Why Loaders? • They are available to every Activity and Fragment. • They provide asynchronous loading of data. • They monitor the source of their data and deliver new results when the content changes. • They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.
  • 54. Using Cursor Loader public class ContactsList extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { ::: @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Initializes the loader. It will use the existing one or // create and start a new one. getLoaderManager().initLoader(ID, null /*bundle*/, this /*callbacks*/); } private void setDataUri(Uri dataUri) { mDataUri = dataUri; // Assuming they are not equal getLoaderManager().restartLoader(ID, null, this); } :::
  • 55. Using Cursor Loader ::: @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), mDataUri, CONTACTS_PROJECITON, null /*selection*/, null /*selArgs*/, Contacts.DISPLAY_NAME); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. The framework will close the old cursor. mAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { // Last cursor is about to be closed. We have to stop using it. mAdapter.swapCursor(null); } }
  • 56. • Volite Javu? • Fokusirani ste na visok kvalitet koda i optimizaciju performansi? • Zainteresovani ste za prelazak na Mobile razvoj? bit.ly/Java2AndroidJava2Android