SlideShare ist ein Scribd-Unternehmen logo
1 von 57
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Dependency Injection with Unity Container
Dependency Injection with Unity ContainerDependency Injection with Unity Container
Dependency Injection with Unity ContainerMindfire Solutions
 
Vaadin 8 with Spring Frameworks AutoConfiguration
Vaadin 8 with Spring Frameworks AutoConfigurationVaadin 8 with Spring Frameworks AutoConfiguration
Vaadin 8 with Spring Frameworks AutoConfigurationPeter Lehto
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice PresentationDmitry Buzdin
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4Naga Muruga
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google GuiceKnoldus 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 ApplicationMicha Kops
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
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.0PhilWinstanley
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014Ran Wahle
 
Jasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casJasigsakai12 columbia-customizes-cas
Jasigsakai12 columbia-customizes-casellentuck
 
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 meetTomasz Michalak
 
Techlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinTechlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinPeter Lehto
 

Was ist angesagt? (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
 

Andere mochten auch

Android Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and PatternsAndroid Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and PatternsAdham Enaya
 
Android Camera Architecture
Android Camera ArchitectureAndroid Camera Architecture
Android Camera ArchitecturePicker Weng
 
Android app dev company in pune
Android app dev company in puneAndroid app dev company in pune
Android app dev company in puneAshish Gujrathi
 
Camera 2.0 in Android 4.2
Camera 2.0 in Android 4.2 Camera 2.0 in Android 4.2
Camera 2.0 in Android 4.2 Balwinder Kaur
 
Clean architecture
Clean architectureClean architecture
Clean architectureandbed
 
Wifi direct p2p app
Wifi direct p2p appWifi direct p2p app
Wifi direct p2p appgeniushkg
 
The Pyramid Pie and the 6 X 6 Rule
The Pyramid Pie and the 6 X 6 RuleThe Pyramid Pie and the 6 X 6 Rule
The Pyramid Pie and the 6 X 6 RuleClarity Thinker
 
Understanding the Android System Server
Understanding the Android System ServerUnderstanding the Android System Server
Understanding the Android System ServerOpersys inc.
 
Android Bluetooth Introduction
Android Bluetooth IntroductionAndroid Bluetooth Introduction
Android Bluetooth IntroductionErin Yueh
 
Android media framework overview
Android media framework overviewAndroid media framework overview
Android media framework overviewJerrin George
 
Android Multimedia Framework
Android Multimedia FrameworkAndroid Multimedia Framework
Android Multimedia FrameworkPicker Weng
 
The Future Of Work & The Work Of The Future
The Future Of Work & The Work Of The FutureThe Future Of Work & The Work Of The Future
The Future Of Work & The Work Of The FutureArturo Pelayo
 

Andere mochten auch (14)

Core Android
Core AndroidCore Android
Core Android
 
Android Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and PatternsAndroid Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and Patterns
 
Android Camera Architecture
Android Camera ArchitectureAndroid Camera Architecture
Android Camera Architecture
 
Android app dev company in pune
Android app dev company in puneAndroid app dev company in pune
Android app dev company in pune
 
Android bluetooth
Android bluetoothAndroid bluetooth
Android bluetooth
 
Camera 2.0 in Android 4.2
Camera 2.0 in Android 4.2 Camera 2.0 in Android 4.2
Camera 2.0 in Android 4.2
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Wifi direct p2p app
Wifi direct p2p appWifi direct p2p app
Wifi direct p2p app
 
The Pyramid Pie and the 6 X 6 Rule
The Pyramid Pie and the 6 X 6 RuleThe Pyramid Pie and the 6 X 6 Rule
The Pyramid Pie and the 6 X 6 Rule
 
Understanding the Android System Server
Understanding the Android System ServerUnderstanding the Android System Server
Understanding the Android System Server
 
Android Bluetooth Introduction
Android Bluetooth IntroductionAndroid Bluetooth Introduction
Android Bluetooth Introduction
 
Android media framework overview
Android media framework overviewAndroid media framework overview
Android media framework overview
 
Android Multimedia Framework
Android Multimedia FrameworkAndroid Multimedia Framework
Android Multimedia Framework
 
The Future Of Work & The Work Of The Future
The Future Of Work & The Work Of The FutureThe Future Of Work & The Work Of The Future
The Future Of Work & The Work Of The Future
 

Ähnlich wie Java Svet - Communication Between Android App Components

Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym 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 AJAXIMC 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 WindowsPhoneMohammad Shaker
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonfNataliya 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.pdfStephanie Locke
 
Android app development basics
Android app development basicsAndroid app development basics
Android app development basicsAnton Narusberg
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
Android apps development
Android apps developmentAndroid apps development
Android apps developmentMonir Zzaman
 
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 Watersmichael.labriola
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis 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 CodeNaresh Jain
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 

Ähnlich wie 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
 

Kürzlich hochgeladen

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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