SlideShare a Scribd company logo
1 of 63
Download to read offline
Android Best
Practices
José Manuel Ortega
DroidCon July 2014
https://techfest.uc3m.es/programa/android-in-practice/
Index
 UI DESIGN
 INCLUDES / REUSING LAYOUTS
 STYLES
 ACTION BAR SEARCH VIEW / PROGRESS BAR
 ACCESSIBILITY / TALLBACK
 NETWORK CONNECTION
 ASYNCTASK / SERVICES
 FRAGMENTS
 NAVIGATION PATTERNS
 GEOLOCATION / PERFORMANCE
 DEPENDENCY INYECTION / ANNOTATIONS
 TOOLS / VOLLEY / LIBRARIES / /BOOKS
http://developer.android.com/intl/es/training/index.html
UI Design
 http://developer.android.com/design/index.html
Ways to specify the size of an item:
 dp/dip: Density independent pixel.
 sp/sip: Scale independent pixel.Used in font
sizes.
 pt: Point.
 px: Pixel. Not use
 layout_width,layout_height
 match_parent:takes all the space
available.
 wrap_content: uses the space needed
 fill_parent:equivalent to match_parent
Android Asset Studio
 Generate icons and graphic elements for each resolution
 http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html
Resources /Screen support
 External elements you want to include and reference in the application.
 Declaratively include in /res ,accesing by @<type>/<nname>
 Are programmatically accessible via the R class
(compiled with Android Asset Packaging Tool)
 Android automatically selects the resource that adapts to the environment
 Each resource type in a folder / res.
 drawable: Images, Icons.
 layout: Layout to organize views.
 values:
 string.xml: Text strings
 colors.xml
 dimens.xml: font sizes,margins,paddings
 anim: Animations
 raw: Other resources like audio or video
 menu: Menus and dialogs
 xml: Other xml (preferences, app widget, …)
<supports-screens android:anyDensity="true"
android:xlargeScreens="true" android:largeScreens="true"
android:normalScreens="true" android:smallScreens="true" />
Includes / Reusing layouts
Styles
<!-- estilo para TextView -->
<style name="CodeStyleTextView"
parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:paddingTop">50dp</item>
<item name="android:textColor">@color/negro</item>
<item name="android:background">@color/gris_claro</item>
<item name="android:textSize">35sp</item>
</style>
<!-- estilo para Button-->
<style name="CodeStyleButton" parent="android:Widget.Button">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">20sp</item>
<item
name="android:drawableTop">@drawable/logo_empresa</item>
</style>
Styles
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/info_empresa"
style="@style/CodeStyleTextView" />
<Button
android:id="@+id/btnChangeImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/cambiar_imagen_fondo"
style="@style/CodeStyleButton" />
Action Bar Search View
Action Bar Search View
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mSearchView = (SearchView) searchItem.getActionView();
mSearchView.setQueryHint("Search...");
mSearchView.setOnQueryTextListener(this);
return true;
}
<item android:id="@+id/action_search"
android:showAsAction="always"
android:title="@string/search"
android:icon="@android:drawable/ic_menu_search"
android:actionViewClass=
"android.support.v7.widget.SearchView" />
private SearchView mSearchView;
Action Bar Search View
 Implement interface OnQueryTextListener
 Override methods onQueryTextSubmit, onQueryTextChange
@Override
public boolean onQueryTextSubmit(String query) {
UniversityListFragment fragmentList =
(UniversityListFragment)getSupportFragmentManager().findFragmentBy
Tag("list_fragment");
fragmentList.searchData(query);
return true;
}
@Override
public boolean onQueryTextChange(String query) {
return true;
}
ACTION BAR PROGRESS
 Avoid modal Dialogues and Activities
 Always update the user on progress(ProgressBar and ProgressDialog)
 Render the main view and fill in data as it arrives
ACTION BAR PROGRESS
 Progress bar in Action Bar while url loading
private Activity activity = this;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.
FEATURE_INDETERMINATE_PROGRESS);
ActionBar ab = getSupportActionBar();
………
}
activity.setProgressBarIndeterminateVisibility(true);
viewer.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
activity.setProgressBarIndeterminateVisibility(false);
}
 Show the progress bar to start loading and hide when finished.
Accessibility / TalkBack
Accessibility
http://developer.android.com/training/accessibility/index.html
<Button
android:id="@+id/button"
android:src="@drawable/button"
android:contentDescription="@string/text_description"/>
 Through layout
 Through code
label.setContentDescription(getText(R.string.text_description));
 Focus navigation. Next view to receive focus when user navigates
<EditText
android:id="@id/editText"
android:layout_alignBottom="@+id/button"
android:layout_toLeftOf="@id/button"
android:nextFocusUp="@+id/button"
android:nextFocusDown="@+id/button"
android:nextFocusLeft="@+id/button"
android:nextFocusRight="@+id/button"
android:nextFocusForward="@+id/button"/>
Network connection
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
ConnectivityManager connectivityManager;
connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
connectivityManager.getActiveNetworkInfo();
Boolean connected = networkInfo != null &&
networkInfo.isAvailable() && networkInfo.isConnected();
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE"/>
Network connection
 Enable Wifi / Check connection type
NetworkInfo wifiInfo=connectivityManager.getNetworkInfo
(ConnectivityManager.TYPE_WIFI);
NetworkInfo
mobileInfo = connectivityManager.getNetworkInfo
(ConnectivityManager.TYPE_MOBILE);
if(wifiInfo.isConnected()){
Toast.makeText(context, "Wifi is connected",
Toast.LENGTH_LONG).show();
}
if(mobileInfo.isConnected()){
Toast.makeText(context, "3G/4G is connected",
Toast.LENGTH_LONG).show();
}
WifiManager wifiManager=(WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"/>
Network connection
 HTTP Request
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
Log.d("isNetworkAvailable", "Checking network connection...");
httpClient.execute(httpGet);
Log.d("isNetworkAvailable", "Connection OK");
return true;
} catch (ClientProtocolException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();
}
return false;
Responsive
Avoid ANR(Application Not Responding)
No response to an input event (such as key press or
screen touch events) within 5 seconds.
Do not block the main UI thread with heavy work
Web Service call, Http Request
Communication with UI Thread is made with:
• Thread / Handler
• ThreadPoolExecutor
• AsyncTask
 Goal of AsyncTask is to take care of thread management for you.
Asynctask
 This class will allow us to perform background tasks without using neither directly nor
Handlers Threads, trying these elements in a fully transparent way to the programmer.
 When we define a AsyncTask class must define the type of three elements, the input
parameters, its progress and outcome.
 Override onPreExecute(),doInBackground(),onPostExecute(),onProgressUpdate()
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Integer... values) {
}
@Override
protected String doInBackground(String... uri) {
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
new RequestTask().execute(url);
Services
 Perform the activity in an AsyncTask.
 Kill the service when the task is complete.
 Leaving a service running when it’s not needed is one of the
worst memory management mistakes an Android app can
make.
 Service problem is always execute in main thread.
 The best way to limit the lifespan of your service is to use an
IntentService, which finishes itself as soon as it's done
handling the intent that started it.
 IntentService always execute in own thread.
 Allows to launch a service in a new thread, avoiding blocking
the main thread.
 Example:ActivityRecognitionService
Fragments
 A fragment represents a certain behavior or a portion of a user
interface activity.
 Multiple fragments can be combined.
 A fragment must always be part of an activity.
 They emerged to provide greater flexibility to build the user interface
 Override methods
@Override
//called when finish onCreate method in activity
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onCreate(Bundle savedInstanceState) {//inicializar
componentes
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,Bundle savedInstanceState) {
}
http://developer.android.com/guide/components/fragments.html
Fragments
 Add a fragment to view
 by layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment
class="com.proyecto.spaincomputing.fragment.UniversidadesFragment"
android:id="@+id/FrgListado"
android:layout_width="375dp"
android:layout_height="match_parent"/>
<fragment
class="com.proyecto.spaincomputing.fragment.FragmentDetalle"
android:id="@+id/FrgDetalle"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Fragments
 Add a fragment to view
 By code
//Fragments array
Fragment[] fragments = new Fragment[]{new PortadaFragment(),
new UniversityListFragment(),new
UniversidadesImagesFragment()};
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.add(R.id.contentFrame, fragments[0])
.add(R.id.contentFrame, fragments[1])
.add(R.id.contentFrame, fragments[2])
.commit();
//show/hide
manager.beginTransaction().show(fragments[0]).commit();
manager.beginTransaction().hide(fragments[1]).commit();
manager.beginTransaction().hide(fragments[2]).commit();
Fragments/ Master-detail
PORTRAITLANDSCAPE
Fragments/ Master-detail
PORTRAIT
LANDSCAPE
Fragments/ Master-detail
 2 layout
 layoutfragment_universidades_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Fragments/ Master-detail
 2 layout
 layout-landfragment_universidades_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="horizontal"
tools:context=".TabsActivity" >
<ListView
android:id="@+id/listView"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1.5">
</ListView>
<fragment
android:id="@+id/fragmentUniversidadInfo"
android:name="com.proyecto.spaincomputing.fragment.UniversidadInfoFragment"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="4"
tools:layout="@layout/fragment_universidad_info" />
</LinearLayout>
Fragments/ Master-detail
 Check orientation to display the detail page
UniversidadBean ub=listado.get(position);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE) {
FragmentManager manager =
getActivity().getSupportFragmentManager();
UniversidadInfoFragment fragment = (UniversidadInfoFragment)
manager.findFragmentById(R.id.fragmentUniversidadInfo);
fragment.loadWebViewContent(ub.getEnlace());
getActivity().invalidateOptionsMenu();
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),
UniversityDetailActivity.class);
intent.putExtra(UniversityDetailActivity.URL, ub.getEnlace());
url=ub.getEnlace();
intent.putExtra(UniversityDetailActivity.UNIVERSIDAD,
ub.getNombre());
startActivity(intent);
}
Navigation patterns
 Navigation drawer
 View Pager
 Tabs navigation in Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
 Drop-down Navigation in Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
 NavUtils in library support
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Navigation Drawer
 http://developer.android.com/training/implementing-navigation/nav-
drawer.html
View Pager
http://developer.android.com/intl/es/training/animation/screen-slide.html
Tabs navigation in Action bar
http://developer.android.com/intl/es/guide/topics/ui/actionbar.html#Tabs
Drop-down navigation in Action bar
http://developer.android.com/intl/es/guide/topics/ui/actionbar.html#Dropdown
NavUtils
import android.support.v4.app.NavUtils;
NavUtils.navigateUpTo(this,
new Intent(this, ListadoActivity.class));
http://developer.android.com/design/patterns/navigation.html
Intent intent = NavUtils.getParentActivityIntent(this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_SINGLE_TOP);
NavUtils.navigateUpTo(this, intent);
NavUtils.navigateUpFromSameTask(this);
<activity android:name=".DetalleUniversidadActivity"
android:parentActivityName=".ListadoActivity"
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".ListadoActivity" />
</activity>
Singleton
 Application class
<application
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@style/Theme.Styled"
android:name=
"com.proyecto.spaincomputing.singleton.MySingleton">
public class MySingleton extends Application
{
private static MySingleton instance;
public static Context context;
public static MySingleton getInstance(Context context){
if (instance == null) { // Create the instance
instance = new MySingleton(context.getApplicationContext());
}
return instance;
}
@Override public void onCreate() {
super.onCreate();
context = getApplicationContext();
}}
Adapter Pattern
 Link between the source data and the view
 It works with ListView or GridView
 There are many types of adapter
 You can perform a custom adapter
 The most used ArrayAdapter / CursorAdapter
 The Adapter interacts with a collection of data objects for display in
View
ArrayList<UniversidadBean>
listado=newArrayList<UniversidadBean>();
private ListView lstListado;
lstListado=(ListView)getView().findViewById
(R.id.LstListado);
lstListado.setAdapter
(new UniversidadAdapter(this,listado));
View Holder/View Container Pattern
 ViewContainer
static class ViewContainer{
public ImageView imagen;
public TextView nombre;
public TextView descripcion;
}
 Improve the performance of listview
 The viewholder is used to avoid calling findViewById whenever prompted a
new row to the adapter. Thus, instead of calling findViewById each time you
use the references to the fields you have stored in the viewholder.
 This pattern will help us to limit the number of calls to findViewById method.
The idea would be to call it once, and then save the view daughter that refers
to the instance of ViewHolder to be associated with the object by the method
convertView View.setTag ()
 Its recommend using a static class to store the items of each row in the view,
functioning as a kind of cache for our view.
View Holder/View Container Pattern
@Override
public View getView(int position, View convertView,ViewGroup parent) {
ViewContainer viewContainer;
//si es la primera vez que se imprime la fila
if(convertView==null){
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.row, null,true);
//crea una vista para el objeto contenedor
viewContainer=new ViewContainer()
//obtiene una referencia a todas las vistas de la fila
viewContainer.nombre=(TextView)convertView.findViewById(R.id.textView_superior);
viewContainer.descripcion=(TextView)convertView.findViewById(R.id.textView_inferior);
viewContainer.imagen=(ImageView)convertView.findViewById(R.id.imageView_imagen);
//asigna el contenedor de la vista a rowView
convertView.setTag(viewContainer);
}else{
viewContainer=(ViewContainer) convertView.getTag(); //recicling }
//personaliza el contenido de cada fila basándone en su posición
viewContainer.nombre.setText(listado.get(position).getNombre());
viewContainer.descripcion.setText(listado.get(position).getDescripcion());
viewContainer.imagen.setImageResource(listado.get(position).getIdImagen());
return(convertView);
}
View Holder/View Container Pattern
 Debug
Criteria Geolocation
 LocationManager / android.location package
 ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION
//Obtain Location Manager
LocationManager locationManager = (LocationManager)this.getSystemService
(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE); //GPS
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // WIFI
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(false);
String provider = locationManager.getBestProvider(criteria, true);
// In order to make sure the device is getting the location, request
// updates [wakeup after changes of: 5 sec. or 10 meter]
locationManager.requestLocationUpdates(provider, 5, 10, this);
locationBridge.setNewLocation(locationManager.getLastKnownLocation(provider
));
Obtain user moving
 LocationListener onLocationChanged()
 Activity Recognition API
<uses-permission android:name="com.google.android-
gms.permission.ACTIVITY_RECOGNITION"/>
<service android:name="ActivityRecognitionService"/>
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.myactivityrecognition.ACTIVITY_RECOGNITION_
DATA");
registerReceiver(receiver, filter);
 Register broadcast receiver on activity
Obtain user moving / ActivityRecognitionService
public class ActivityRecognitionService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
if(ActivityRecognitionResult.hasResult(intent)){
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
Intent i = new
Intent("com.example.myactivityrecognition.ACTIVITY_RECOGNITION_DATA");
i.putExtra("Activity", getType(result.getMostProbableActivity().getType()) );
i.putExtra("Confidence", result.getMostProbableActivity().getConfidence());
sendBroadcast(i);
}
}
private String getType(int type){
if(type == DetectedActivity.UNKNOWN)
return "Unknown";
else if(type == DetectedActivity.IN_VEHICLE)
return "In Vehicle";
else if(type == DetectedActivity.ON_BICYCLE)
return "On Bicycle";
else if(type == DetectedActivity.ON_FOOT)
return "On Foot";
else
return "";
} }
Performance / Save Battery life
 Useful for background tracking applications
 Use “PASSIVE_PROVIDER” LocationProvider
(instead of “GPS_PROVIDER”)
 LocationListener has three primary settings:
“provider” positioning technology (e.g. GPS, NETWORK)
“minTime” requested time (milliseconds) between location
updates
“minDistance” requested distance (m) that triggers updates
if (user_moving){
-Decrease LocationListener “minTime”
} else{
if(Stopped for a reasonable amount of time){
-Increase LocationListener “minTime”
}
}
Performance /Instruction count
Debug.InstructionCount icount =new
Debug.InstructionCount();
icount.resetAndStart();
……….
if(icount.collect()){
Log.d("DEBUG","Total instructions
executed"+icount.globalTotal());
Log.d("DEBUG","Method
invocations"+icount.globalMethodInvocations());
}
DEPENDENCY INYECTION
 RoboGuice / Dagger / ButterKnife
 RoboGuice is a framework that brings the simplicity and ease of
Dependency Injection to Android.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (TextView) findViewById(R.id.name);
myName = getString(R.string.app_name);
name.setText("Hello, " + myName);
}
@ ContentView(R.layout.main)
class MyActivity extends RoboActivity{
@InjectView(R.id.name) TextView name;
@InjectView(R.id.thumbnail) ImageView thumbnail;
@InjectResource(R.drawable.icon) Drawable icon;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name.setText("Hello, " + myName);
}}
ButterKnife
 Eliminate findViewById calls by using @InjectView
 Eliminate anonymous inner-classes for listeners by annotating
methods with @OnClick
class ExampleActivity extends Activity {
@InjectView(R.id.name) EditText name;
@OnClick(R.id.submit) void submit() {
}
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.inject(this);
}
}
https://github.com/JakeWharton/butterknife
Annotations
@EActivity(R.layout.translate) // Sets content view to R.layout.translate
public class TranslateActivity extends Activity {
@ViewById // Injects R.id.textInput
EditText textInput;
@ViewById(R.id.myTextView) // Injects R.id.myTextView
TextView result;
@AnimationRes // Injects android.R.anim.fade_in
Animation fadeIn;
@Click // When R.id.doTranslate button is clicked
void doTranslate() {
translateInBackground(textInput.getText().toString());
}
@Background // Executed in a background thread
void translateInBackground(String textToTranslate) {
String translatedText = callGoogleTranslate(textToTranslate);
showResult(translatedText);
}
@UiThread // Executed in the ui thread
void showResult(String translatedText) {
result.setText(translatedText);
result.startAnimation(fadeIn);
}
http://androidannotations.org/
Features
 Check for API availability before using features
PackageManager pm = getPackageManager();
boolean hasCamera =
pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (hasCamera) {
// do things that require the camera
}
boolean hasBlueTooth =
pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
if (hasBlueTooth) {
// do things that require the blueTooth
}
<uses-feature android:name="android.hardware.bluetooth"/>
<uses-feature android:name="android.hardware.camera"/>
Restore state in activity
• If you support both orientations, save the instance state while
orientation changes for more responsiveness.
 Before finish() an activity, onSaveInstanceState() is called to save UI
state.
 Restore the Activity state after being created
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
}
LINT
 Android comes with a tool called lint that can be used for
identifying and correcting structural problems with your code.
 Each detection has an associated description and severity level
so it can be prioritized.
 Can be invoked directly from the command-line, automated build
system or directly from Eclipse
VOLLEY
https://android.googlesource.com/platform/frameworks/volley
https://github.com/mcxiaoke/android-volley
 Unzip and import from Eclipse as a new project with code available. Export
the project as Java Volley / jar checking only the "src" folder.
 Volley is a library that facilitates and speeds up the creation of applications
that make use of networking in Android handling concurrency and network
requests.
 The advantage is that volley is responsible for managing the request threads
transparently to the developer.
 libsvolley.jar
 Objects
 RequestQueue
 Request: Contains all the necessary details of API calls to Web. For example,
the method to use (GET or POST), application data, listeners, error listeners.
VOLLEY REQUEST
import com.android.volley.*;
public static RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestQueue = Volley.newRequestQueue(this);
}
 JSON Request with volley.Request object
JsonObjectRequest jsObjRequest = new
JsonObjectRequest(Request.Method.GET, url, null,
successListener,null);
requestQueue.add(jsObjRequest);
 Instagram Activity
VOLLEY RESPONSE
//Callback that is executed once the request has completed
Response.Listener<JSONObject> successListener =
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
}
}
 JSON Response by volley.Response object
 More volley examples
https://github.com/PareshMayani/Android-Volley-Example
Images
 LRU
Cache
 Other libraries
https://github.com/nostra13/Android-Universal-Image-Loader
• Universal Image Loader
http://square.github.io/picasso/
• Picasso
Volley image loader
public InstagramImageAdapter(Context context,
ArrayList<InstagramImage> dataArray) {
this.dataArray = dataArray;
this.inflater = LayoutInflater.from(context);
this.imageLoader = new
ImageLoader(InstagramActivity.requestQueue,
new BitmapLRUCache());
}
private InstagramImageAdapter adapter;
private ArrayList<InstagramImage> imagArray;
imagArray=new ArrayList<InstagramImage>();
adapter=new InstagramImageAdapter(this,imagArray);
Response.Listener<JSONObject> successListener =
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
JSONArray data = response.getJSONArray("data");
imagArray.addImage(data);
}
Developer libraries in google play
Libraries
 Indicator in ViewPager
 http://viewpagerindicator.com/
 https://github.com/chrisbanes/ActionBar-PullToRefresh
 Pager Sliding Tabstrip
 https://github.com/astuetz/PagerSlidingTabStrip
 Show routes in map.
 https://github.com/tyczj/MapNavigator
Sliding Menu
 Library to implement a sliding flyout with similar behavior to
navigation drawer
 https://github.com/jfeinstein10/SlidingMenu
MessageBar
 Library to improve toast messages
 http://simonvt.github.io/MessageBar/
Fading Action Bar
 Used in Google play music
 https://github.com/ManuelPeinado/FadingActionBar
+
 http://www.androidviews.net/  http://www.androidpatterns.com/
Books
About me
https://github.com/jmortega/apps
https://github.com/jmortega/android
https://www.linkedin.com/in/jmortega1
@jmortegac
https://play.google.com/store/apps/developer?id=Jos%C3%A9+Manuel+Ortega+Candel
https://speakerdeck.com/jmortega/

More Related Content

What's hot

06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and ContainerOum Saokosal
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018Somkiat Khitwongwattana
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?Brenda Cook
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android FragmentsSergi Martínez
 
Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談awonwon
 
Andriod dev toolbox part 2
Andriod dev toolbox  part 2Andriod dev toolbox  part 2
Andriod dev toolbox part 2Shem Magnezi
 
The Glass Class - Tutorial 4 - GDK-Live Cards
The Glass Class - Tutorial 4 - GDK-Live CardsThe Glass Class - Tutorial 4 - GDK-Live Cards
The Glass Class - Tutorial 4 - GDK-Live CardsGun Lee
 
Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricksShem Magnezi
 
Android UI Testing with Espresso
Android UI Testing with EspressoAndroid UI Testing with Espresso
Android UI Testing with EspressoGary Cheng
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & IntentsLope Emano
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updatedGhanaGTUG
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfacesC.o. Nieto
 
Android testing calabash
Android testing calabashAndroid testing calabash
Android testing calabashkellinreaver
 
Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010
Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010
Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010Skills Matter
 

What's hot (20)

06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Android UI Fundamentals part 1
Android UI Fundamentals part 1Android UI Fundamentals part 1
Android UI Fundamentals part 1
 
Ch2 first app
Ch2 first appCh2 first app
Ch2 first app
 
What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018What's new in Android P @ I/O Extended Bangkok 2018
What's new in Android P @ I/O Extended Bangkok 2018
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談
 
Andriod dev toolbox part 2
Andriod dev toolbox  part 2Andriod dev toolbox  part 2
Andriod dev toolbox part 2
 
The Glass Class - Tutorial 4 - GDK-Live Cards
The Glass Class - Tutorial 4 - GDK-Live CardsThe Glass Class - Tutorial 4 - GDK-Live Cards
The Glass Class - Tutorial 4 - GDK-Live Cards
 
Android Components
Android ComponentsAndroid Components
Android Components
 
Xxx
XxxXxx
Xxx
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
Android ui tips & tricks
Android ui tips & tricksAndroid ui tips & tricks
Android ui tips & tricks
 
Android UI Testing with Espresso
Android UI Testing with EspressoAndroid UI Testing with Espresso
Android UI Testing with Espresso
 
Android development - Activities, Views & Intents
Android development - Activities, Views & IntentsAndroid development - Activities, Views & Intents
Android development - Activities, Views & Intents
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updated
 
04 user interfaces
04 user interfaces04 user interfaces
04 user interfaces
 
Android testing calabash
Android testing calabashAndroid testing calabash
Android testing calabash
 
Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010
Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010
Droidcon: Sean Owen: Driving Downloads via Intents- 29/10/2010
 

Viewers also liked

Android best practices 2015
Android best practices 2015Android best practices 2015
Android best practices 2015Sean Katz
 
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAndroid Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAnuradha Weeraman
 
Design Patterns every Android developer should know
Design Patterns every Android developer should knowDesign Patterns every Android developer should know
Design Patterns every Android developer should knowmuratcanbur
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices Amgad Muhammad
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentReto Meier
 
Os Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual MemoryOs Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual Memorysgpraju
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating SystemRaj Mohan
 

Viewers also liked (9)

Android best practices 2015
Android best practices 2015Android best practices 2015
Android best practices 2015
 
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAndroid Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the Trenches
 
Design Patterns every Android developer should know
Design Patterns every Android developer should knowDesign Patterns every Android developer should know
Design Patterns every Android developer should know
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
 
Paging
PagingPaging
Paging
 
Paging and segmentation
Paging and segmentationPaging and segmentation
Paging and segmentation
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android Development
 
Os Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual MemoryOs Swapping, Paging, Segmentation and Virtual Memory
Os Swapping, Paging, Segmentation and Virtual Memory
 
Paging and Segmentation in Operating System
Paging and Segmentation in Operating SystemPaging and Segmentation in Operating System
Paging and Segmentation in Operating System
 

Similar to Android best practices

2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageabilityDaniel Fisher
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2wiradikusuma
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsPSTechSerbia
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + SpringBryan Hsueh
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!DataArt
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginnersDivakar Gu
 
The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]Nilhcem
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developersPavel Lahoda
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon Berlin
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptdavejohnson
 

Similar to Android best practices (20)

2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Android 3
Android 3Android 3
Android 3
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Android
AndroidAndroid
Android
 
The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]The 2016 Android Developer Toolbox [MOBILIZATION]
The 2016 Android Developer Toolbox [MOBILIZATION]
 
Improving android experience for both users and developers
Improving android experience for both users and developersImproving android experience for both users and developers
Improving android experience for both users and developers
 
Droidcon2013 android experience lahoda
Droidcon2013 android experience lahodaDroidcon2013 android experience lahoda
Droidcon2013 android experience lahoda
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
 

More from Jose Manuel Ortega Candel

Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfAsegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfJose Manuel Ortega Candel
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfPyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfJose Manuel Ortega Candel
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfEvolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfJose Manuel Ortega Candel
 
Implementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfImplementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfJose Manuel Ortega Candel
 
Seguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudSeguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudJose Manuel Ortega Candel
 
Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Jose Manuel Ortega Candel
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Jose Manuel Ortega Candel
 
Sharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sSharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sJose Manuel Ortega Candel
 
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Jose Manuel Ortega Candel
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanShodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanJose Manuel Ortega Candel
 
ELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamJose Manuel Ortega Candel
 
Monitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsMonitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsJose Manuel Ortega Candel
 
Python memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorPython memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorJose Manuel Ortega Candel
 

More from Jose Manuel Ortega Candel (20)

Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfAsegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfPyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdf
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
 
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops
 
Evolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfEvolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdf
 
Implementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfImplementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdf
 
Computación distribuida usando Python
Computación distribuida usando PythonComputación distribuida usando Python
Computación distribuida usando Python
 
Seguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudSeguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloud
 
Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python
 
Sharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sSharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8s
 
Implementing cert-manager in K8s
Implementing cert-manager in K8sImplementing cert-manager in K8s
Implementing cert-manager in K8s
 
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)
 
Python para equipos de ciberseguridad
Python para equipos de ciberseguridad Python para equipos de ciberseguridad
Python para equipos de ciberseguridad
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanShodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
 
ELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue Team
 
Monitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsMonitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source tools
 
Python Memory Management 101(Europython)
Python Memory Management 101(Europython)Python Memory Management 101(Europython)
Python Memory Management 101(Europython)
 
SecDevOps containers
SecDevOps containersSecDevOps containers
SecDevOps containers
 
Python memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorPython memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collector
 

Recently uploaded

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
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
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
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.
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
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)
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
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...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
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 ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
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...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

Android best practices

  • 1. Android Best Practices José Manuel Ortega DroidCon July 2014
  • 3. Index  UI DESIGN  INCLUDES / REUSING LAYOUTS  STYLES  ACTION BAR SEARCH VIEW / PROGRESS BAR  ACCESSIBILITY / TALLBACK  NETWORK CONNECTION  ASYNCTASK / SERVICES  FRAGMENTS  NAVIGATION PATTERNS  GEOLOCATION / PERFORMANCE  DEPENDENCY INYECTION / ANNOTATIONS  TOOLS / VOLLEY / LIBRARIES / /BOOKS http://developer.android.com/intl/es/training/index.html
  • 4. UI Design  http://developer.android.com/design/index.html Ways to specify the size of an item:  dp/dip: Density independent pixel.  sp/sip: Scale independent pixel.Used in font sizes.  pt: Point.  px: Pixel. Not use  layout_width,layout_height  match_parent:takes all the space available.  wrap_content: uses the space needed  fill_parent:equivalent to match_parent
  • 5. Android Asset Studio  Generate icons and graphic elements for each resolution  http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html
  • 6. Resources /Screen support  External elements you want to include and reference in the application.  Declaratively include in /res ,accesing by @<type>/<nname>  Are programmatically accessible via the R class (compiled with Android Asset Packaging Tool)  Android automatically selects the resource that adapts to the environment  Each resource type in a folder / res.  drawable: Images, Icons.  layout: Layout to organize views.  values:  string.xml: Text strings  colors.xml  dimens.xml: font sizes,margins,paddings  anim: Animations  raw: Other resources like audio or video  menu: Menus and dialogs  xml: Other xml (preferences, app widget, …) <supports-screens android:anyDensity="true" android:xlargeScreens="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" />
  • 8. Styles <!-- estilo para TextView --> <style name="CodeStyleTextView" parent="@android:style/TextAppearance.Medium"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:paddingTop">50dp</item> <item name="android:textColor">@color/negro</item> <item name="android:background">@color/gris_claro</item> <item name="android:textSize">35sp</item> </style> <!-- estilo para Button--> <style name="CodeStyleButton" parent="android:Widget.Button"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textSize">20sp</item> <item name="android:drawableTop">@drawable/logo_empresa</item> </style>
  • 11. Action Bar Search View @Override public boolean onCreateOptionsMenu(Menu menu) { mSearchView = (SearchView) searchItem.getActionView(); mSearchView.setQueryHint("Search..."); mSearchView.setOnQueryTextListener(this); return true; } <item android:id="@+id/action_search" android:showAsAction="always" android:title="@string/search" android:icon="@android:drawable/ic_menu_search" android:actionViewClass= "android.support.v7.widget.SearchView" /> private SearchView mSearchView;
  • 12. Action Bar Search View  Implement interface OnQueryTextListener  Override methods onQueryTextSubmit, onQueryTextChange @Override public boolean onQueryTextSubmit(String query) { UniversityListFragment fragmentList = (UniversityListFragment)getSupportFragmentManager().findFragmentBy Tag("list_fragment"); fragmentList.searchData(query); return true; } @Override public boolean onQueryTextChange(String query) { return true; }
  • 13. ACTION BAR PROGRESS  Avoid modal Dialogues and Activities  Always update the user on progress(ProgressBar and ProgressDialog)  Render the main view and fill in data as it arrives
  • 14. ACTION BAR PROGRESS  Progress bar in Action Bar while url loading private Activity activity = this; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getWindow().requestFeature(Window. FEATURE_INDETERMINATE_PROGRESS); ActionBar ab = getSupportActionBar(); ……… } activity.setProgressBarIndeterminateVisibility(true); viewer.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { activity.setProgressBarIndeterminateVisibility(false); }  Show the progress bar to start loading and hide when finished.
  • 16. Accessibility http://developer.android.com/training/accessibility/index.html <Button android:id="@+id/button" android:src="@drawable/button" android:contentDescription="@string/text_description"/>  Through layout  Through code label.setContentDescription(getText(R.string.text_description));  Focus navigation. Next view to receive focus when user navigates <EditText android:id="@id/editText" android:layout_alignBottom="@+id/button" android:layout_toLeftOf="@id/button" android:nextFocusUp="@+id/button" android:nextFocusDown="@+id/button" android:nextFocusLeft="@+id/button" android:nextFocusRight="@+id/button" android:nextFocusForward="@+id/button"/>
  • 17. Network connection import android.net.ConnectivityManager; import android.net.NetworkInfo; ConnectivityManager connectivityManager; connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); Boolean connected = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected(); <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  • 18. Network connection  Enable Wifi / Check connection type NetworkInfo wifiInfo=connectivityManager.getNetworkInfo (ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo (ConnectivityManager.TYPE_MOBILE); if(wifiInfo.isConnected()){ Toast.makeText(context, "Wifi is connected", Toast.LENGTH_LONG).show(); } if(mobileInfo.isConnected()){ Toast.makeText(context, "3G/4G is connected", Toast.LENGTH_LONG).show(); } WifiManager wifiManager=(WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(true); <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
  • 19. Network connection  HTTP Request HttpGet httpGet = new HttpGet("http://www.google.com"); HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); try { Log.d("isNetworkAvailable", "Checking network connection..."); httpClient.execute(httpGet); Log.d("isNetworkAvailable", "Connection OK"); return true; } catch (ClientProtocolException e) {e.printStackTrace(); } catch (IOException e) {e.printStackTrace(); } return false;
  • 20. Responsive Avoid ANR(Application Not Responding) No response to an input event (such as key press or screen touch events) within 5 seconds. Do not block the main UI thread with heavy work Web Service call, Http Request Communication with UI Thread is made with: • Thread / Handler • ThreadPoolExecutor • AsyncTask  Goal of AsyncTask is to take care of thread management for you.
  • 21. Asynctask  This class will allow us to perform background tasks without using neither directly nor Handlers Threads, trying these elements in a fully transparent way to the programmer.  When we define a AsyncTask class must define the type of three elements, the input parameters, its progress and outcome.  Override onPreExecute(),doInBackground(),onPostExecute(),onProgressUpdate() class RequestTask extends AsyncTask<String, String, String>{ @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Integer... values) { } @Override protected String doInBackground(String... uri) { } @Override protected void onPostExecute(String result) { super.onPostExecute(result); } new RequestTask().execute(url);
  • 22. Services  Perform the activity in an AsyncTask.  Kill the service when the task is complete.  Leaving a service running when it’s not needed is one of the worst memory management mistakes an Android app can make.  Service problem is always execute in main thread.  The best way to limit the lifespan of your service is to use an IntentService, which finishes itself as soon as it's done handling the intent that started it.  IntentService always execute in own thread.  Allows to launch a service in a new thread, avoiding blocking the main thread.  Example:ActivityRecognitionService
  • 23. Fragments  A fragment represents a certain behavior or a portion of a user interface activity.  Multiple fragments can be combined.  A fragment must always be part of an activity.  They emerged to provide greater flexibility to build the user interface  Override methods @Override //called when finish onCreate method in activity public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public void onCreate(Bundle savedInstanceState) {//inicializar componentes super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { } http://developer.android.com/guide/components/fragments.html
  • 24. Fragments  Add a fragment to view  by layout xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <fragment class="com.proyecto.spaincomputing.fragment.UniversidadesFragment" android:id="@+id/FrgListado" android:layout_width="375dp" android:layout_height="match_parent"/> <fragment class="com.proyecto.spaincomputing.fragment.FragmentDetalle" android:id="@+id/FrgDetalle" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
  • 25. Fragments  Add a fragment to view  By code //Fragments array Fragment[] fragments = new Fragment[]{new PortadaFragment(), new UniversityListFragment(),new UniversidadesImagesFragment()}; FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction() .add(R.id.contentFrame, fragments[0]) .add(R.id.contentFrame, fragments[1]) .add(R.id.contentFrame, fragments[2]) .commit(); //show/hide manager.beginTransaction().show(fragments[0]).commit(); manager.beginTransaction().hide(fragments[1]).commit(); manager.beginTransaction().hide(fragments[2]).commit();
  • 28. Fragments/ Master-detail  2 layout  layoutfragment_universidades_list.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout>
  • 29. Fragments/ Master-detail  2 layout  layout-landfragment_universidades_list.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="horizontal" tools:context=".TabsActivity" > <ListView android:id="@+id/listView" android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight="1.5"> </ListView> <fragment android:id="@+id/fragmentUniversidadInfo" android:name="com.proyecto.spaincomputing.fragment.UniversidadInfoFragment" android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight="4" tools:layout="@layout/fragment_universidad_info" /> </LinearLayout>
  • 30. Fragments/ Master-detail  Check orientation to display the detail page UniversidadBean ub=listado.get(position); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { FragmentManager manager = getActivity().getSupportFragmentManager(); UniversidadInfoFragment fragment = (UniversidadInfoFragment) manager.findFragmentById(R.id.fragmentUniversidadInfo); fragment.loadWebViewContent(ub.getEnlace()); getActivity().invalidateOptionsMenu(); } else { Intent intent = new Intent(getActivity().getApplicationContext(), UniversityDetailActivity.class); intent.putExtra(UniversityDetailActivity.URL, ub.getEnlace()); url=ub.getEnlace(); intent.putExtra(UniversityDetailActivity.UNIVERSIDAD, ub.getNombre()); startActivity(intent); }
  • 31. Navigation patterns  Navigation drawer  View Pager  Tabs navigation in Action Bar actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);  Drop-down Navigation in Action Bar actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);  NavUtils in library support <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pager" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  • 34. Tabs navigation in Action bar http://developer.android.com/intl/es/guide/topics/ui/actionbar.html#Tabs
  • 35. Drop-down navigation in Action bar http://developer.android.com/intl/es/guide/topics/ui/actionbar.html#Dropdown
  • 36. NavUtils import android.support.v4.app.NavUtils; NavUtils.navigateUpTo(this, new Intent(this, ListadoActivity.class)); http://developer.android.com/design/patterns/navigation.html Intent intent = NavUtils.getParentActivityIntent(this); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP); NavUtils.navigateUpTo(this, intent); NavUtils.navigateUpFromSameTask(this); <activity android:name=".DetalleUniversidadActivity" android:parentActivityName=".ListadoActivity" <!-- Parent activity meta-data to support 4.0 and lower --> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".ListadoActivity" /> </activity>
  • 37. Singleton  Application class <application android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/Theme.Styled" android:name= "com.proyecto.spaincomputing.singleton.MySingleton"> public class MySingleton extends Application { private static MySingleton instance; public static Context context; public static MySingleton getInstance(Context context){ if (instance == null) { // Create the instance instance = new MySingleton(context.getApplicationContext()); } return instance; } @Override public void onCreate() { super.onCreate(); context = getApplicationContext(); }}
  • 38. Adapter Pattern  Link between the source data and the view  It works with ListView or GridView  There are many types of adapter  You can perform a custom adapter  The most used ArrayAdapter / CursorAdapter  The Adapter interacts with a collection of data objects for display in View ArrayList<UniversidadBean> listado=newArrayList<UniversidadBean>(); private ListView lstListado; lstListado=(ListView)getView().findViewById (R.id.LstListado); lstListado.setAdapter (new UniversidadAdapter(this,listado));
  • 39. View Holder/View Container Pattern  ViewContainer static class ViewContainer{ public ImageView imagen; public TextView nombre; public TextView descripcion; }  Improve the performance of listview  The viewholder is used to avoid calling findViewById whenever prompted a new row to the adapter. Thus, instead of calling findViewById each time you use the references to the fields you have stored in the viewholder.  This pattern will help us to limit the number of calls to findViewById method. The idea would be to call it once, and then save the view daughter that refers to the instance of ViewHolder to be associated with the object by the method convertView View.setTag ()  Its recommend using a static class to store the items of each row in the view, functioning as a kind of cache for our view.
  • 40. View Holder/View Container Pattern @Override public View getView(int position, View convertView,ViewGroup parent) { ViewContainer viewContainer; //si es la primera vez que se imprime la fila if(convertView==null){ LayoutInflater inflater = context.getLayoutInflater(); convertView = inflater.inflate(R.layout.row, null,true); //crea una vista para el objeto contenedor viewContainer=new ViewContainer() //obtiene una referencia a todas las vistas de la fila viewContainer.nombre=(TextView)convertView.findViewById(R.id.textView_superior); viewContainer.descripcion=(TextView)convertView.findViewById(R.id.textView_inferior); viewContainer.imagen=(ImageView)convertView.findViewById(R.id.imageView_imagen); //asigna el contenedor de la vista a rowView convertView.setTag(viewContainer); }else{ viewContainer=(ViewContainer) convertView.getTag(); //recicling } //personaliza el contenido de cada fila basándone en su posición viewContainer.nombre.setText(listado.get(position).getNombre()); viewContainer.descripcion.setText(listado.get(position).getDescripcion()); viewContainer.imagen.setImageResource(listado.get(position).getIdImagen()); return(convertView); }
  • 41. View Holder/View Container Pattern  Debug
  • 42. Criteria Geolocation  LocationManager / android.location package  ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION //Obtain Location Manager LocationManager locationManager = (LocationManager)this.getSystemService (Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); //criteria.setAccuracy(Criteria.ACCURACY_FINE); //GPS criteria.setAccuracy(Criteria.ACCURACY_COARSE); // WIFI criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setSpeedRequired(false); criteria.setCostAllowed(false); String provider = locationManager.getBestProvider(criteria, true); // In order to make sure the device is getting the location, request // updates [wakeup after changes of: 5 sec. or 10 meter] locationManager.requestLocationUpdates(provider, 5, 10, this); locationBridge.setNewLocation(locationManager.getLastKnownLocation(provider ));
  • 43. Obtain user moving  LocationListener onLocationChanged()  Activity Recognition API <uses-permission android:name="com.google.android- gms.permission.ACTIVITY_RECOGNITION"/> <service android:name="ActivityRecognitionService"/> IntentFilter filter = new IntentFilter(); filter.addAction("com.example.myactivityrecognition.ACTIVITY_RECOGNITION_ DATA"); registerReceiver(receiver, filter);  Register broadcast receiver on activity
  • 44. Obtain user moving / ActivityRecognitionService public class ActivityRecognitionService extends IntentService { @Override protected void onHandleIntent(Intent intent) { if(ActivityRecognitionResult.hasResult(intent)){ ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); Intent i = new Intent("com.example.myactivityrecognition.ACTIVITY_RECOGNITION_DATA"); i.putExtra("Activity", getType(result.getMostProbableActivity().getType()) ); i.putExtra("Confidence", result.getMostProbableActivity().getConfidence()); sendBroadcast(i); } } private String getType(int type){ if(type == DetectedActivity.UNKNOWN) return "Unknown"; else if(type == DetectedActivity.IN_VEHICLE) return "In Vehicle"; else if(type == DetectedActivity.ON_BICYCLE) return "On Bicycle"; else if(type == DetectedActivity.ON_FOOT) return "On Foot"; else return ""; } }
  • 45. Performance / Save Battery life  Useful for background tracking applications  Use “PASSIVE_PROVIDER” LocationProvider (instead of “GPS_PROVIDER”)  LocationListener has three primary settings: “provider” positioning technology (e.g. GPS, NETWORK) “minTime” requested time (milliseconds) between location updates “minDistance” requested distance (m) that triggers updates if (user_moving){ -Decrease LocationListener “minTime” } else{ if(Stopped for a reasonable amount of time){ -Increase LocationListener “minTime” } }
  • 46. Performance /Instruction count Debug.InstructionCount icount =new Debug.InstructionCount(); icount.resetAndStart(); ………. if(icount.collect()){ Log.d("DEBUG","Total instructions executed"+icount.globalTotal()); Log.d("DEBUG","Method invocations"+icount.globalMethodInvocations()); }
  • 47. DEPENDENCY INYECTION  RoboGuice / Dagger / ButterKnife  RoboGuice is a framework that brings the simplicity and ease of Dependency Injection to Android. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name = (TextView) findViewById(R.id.name); myName = getString(R.string.app_name); name.setText("Hello, " + myName); } @ ContentView(R.layout.main) class MyActivity extends RoboActivity{ @InjectView(R.id.name) TextView name; @InjectView(R.id.thumbnail) ImageView thumbnail; @InjectResource(R.drawable.icon) Drawable icon; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); name.setText("Hello, " + myName); }}
  • 48. ButterKnife  Eliminate findViewById calls by using @InjectView  Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick class ExampleActivity extends Activity { @InjectView(R.id.name) EditText name; @OnClick(R.id.submit) void submit() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.inject(this); } } https://github.com/JakeWharton/butterknife
  • 49. Annotations @EActivity(R.layout.translate) // Sets content view to R.layout.translate public class TranslateActivity extends Activity { @ViewById // Injects R.id.textInput EditText textInput; @ViewById(R.id.myTextView) // Injects R.id.myTextView TextView result; @AnimationRes // Injects android.R.anim.fade_in Animation fadeIn; @Click // When R.id.doTranslate button is clicked void doTranslate() { translateInBackground(textInput.getText().toString()); } @Background // Executed in a background thread void translateInBackground(String textToTranslate) { String translatedText = callGoogleTranslate(textToTranslate); showResult(translatedText); } @UiThread // Executed in the ui thread void showResult(String translatedText) { result.setText(translatedText); result.startAnimation(fadeIn); } http://androidannotations.org/
  • 50. Features  Check for API availability before using features PackageManager pm = getPackageManager(); boolean hasCamera = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA); if (hasCamera) { // do things that require the camera } boolean hasBlueTooth = pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH); if (hasBlueTooth) { // do things that require the blueTooth } <uses-feature android:name="android.hardware.bluetooth"/> <uses-feature android:name="android.hardware.camera"/>
  • 51. Restore state in activity • If you support both orientations, save the instance state while orientation changes for more responsiveness.  Before finish() an activity, onSaveInstanceState() is called to save UI state.  Restore the Activity state after being created @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState); } public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState); }
  • 52. LINT  Android comes with a tool called lint that can be used for identifying and correcting structural problems with your code.  Each detection has an associated description and severity level so it can be prioritized.  Can be invoked directly from the command-line, automated build system or directly from Eclipse
  • 53. VOLLEY https://android.googlesource.com/platform/frameworks/volley https://github.com/mcxiaoke/android-volley  Unzip and import from Eclipse as a new project with code available. Export the project as Java Volley / jar checking only the "src" folder.  Volley is a library that facilitates and speeds up the creation of applications that make use of networking in Android handling concurrency and network requests.  The advantage is that volley is responsible for managing the request threads transparently to the developer.  libsvolley.jar  Objects  RequestQueue  Request: Contains all the necessary details of API calls to Web. For example, the method to use (GET or POST), application data, listeners, error listeners.
  • 54. VOLLEY REQUEST import com.android.volley.*; public static RequestQueue requestQueue; @Override protected void onCreate(Bundle savedInstanceState) { requestQueue = Volley.newRequestQueue(this); }  JSON Request with volley.Request object JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, successListener,null); requestQueue.add(jsObjRequest);  Instagram Activity
  • 55. VOLLEY RESPONSE //Callback that is executed once the request has completed Response.Listener<JSONObject> successListener = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { } }  JSON Response by volley.Response object  More volley examples https://github.com/PareshMayani/Android-Volley-Example
  • 56. Images  LRU Cache  Other libraries https://github.com/nostra13/Android-Universal-Image-Loader • Universal Image Loader http://square.github.io/picasso/ • Picasso
  • 57. Volley image loader public InstagramImageAdapter(Context context, ArrayList<InstagramImage> dataArray) { this.dataArray = dataArray; this.inflater = LayoutInflater.from(context); this.imageLoader = new ImageLoader(InstagramActivity.requestQueue, new BitmapLRUCache()); } private InstagramImageAdapter adapter; private ArrayList<InstagramImage> imagArray; imagArray=new ArrayList<InstagramImage>(); adapter=new InstagramImageAdapter(this,imagArray); Response.Listener<JSONObject> successListener = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { JSONArray data = response.getJSONArray("data"); imagArray.addImage(data); }
  • 58. Developer libraries in google play
  • 59. Libraries  Indicator in ViewPager  http://viewpagerindicator.com/  https://github.com/chrisbanes/ActionBar-PullToRefresh  Pager Sliding Tabstrip  https://github.com/astuetz/PagerSlidingTabStrip  Show routes in map.  https://github.com/tyczj/MapNavigator
  • 60. Sliding Menu  Library to implement a sliding flyout with similar behavior to navigation drawer  https://github.com/jfeinstein10/SlidingMenu MessageBar  Library to improve toast messages  http://simonvt.github.io/MessageBar/
  • 61. Fading Action Bar  Used in Google play music  https://github.com/ManuelPeinado/FadingActionBar +  http://www.androidviews.net/  http://www.androidpatterns.com/
  • 62. Books