0
ANDROIDDoes not Suck anymore!
Andy RubinNo plans to leave Google. Oh, and just formeme completeness -- there are over 900,000android devices activated e...
Android evolves
Android Design Patternshttp://developer.android.com/design/index.html
No More Menu Button
New Buttons
Notifications
Navigation
ActionBar
Action Bar Selection
MultiPane
Dialogs
Android is not ios
IOS DesignIt was cool 2 years ago
Android is not ios
Fragmentation
Fragmentation
Fragmentation
Shut up and Show me Code Bitch!
Android Support Jar●   V4                             ●   V13●   Fragment                       ●   FragmentCompat●   Frag...
Support JarJust change the import and use latest apis                It rocks!!!
Fragment●   Tablet and phone code comes together●   One ring to rule them all!!!
FragmentDefine in XML<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_...
Create FragmentDetailsFragment f = new DetailsFragment();    // Supply index input as an argument.    Bundle args = new Bu...
Fire the fragment// Instantiate a new fragment. Fragment newFragment = CountingFragment.newInstance(mStackLevel); // Add t...
Get the parameters@Override public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);    ...
Use XMLAs much as you can
Inflate Views●   Design using XML●   And @javaView v = inflater.inflate(R.layout.hello_world, container, false); View tv =...
DialogFragmentBetter Back button supportpublic static class MyDialogFragment extends DialogFragment {
Other Fragments●   ListFragment●   PreferenceFragment
Loaders●   Loader Callback MethodsonCreateLoader()OnLoadFinished()onLoaderReset()
Great Man●   Jack Whartonhttps://github.com/JakeWharton
Libraries●   ActionBarSherlock●   ActivityCompat2●   NotificationCompat2●   NineOldAndroids●   SwipeToDismissNOA●   Androi...
ActionBarSherlock●   At last you can use great ActionBar●   Just usegetSupportActionBar()●   Instead ofgetActionBar()
NineOldAndroids ●   ObjectAnimator.ofFloat(myObject, "translationY", -myObject.getHeight()).start();AnimatorSet set = new ...
ViewPagerIndicatorXML<com.viewpagerindicator.TitlePageIndicator  android:id="@+id/titles"  android:layout_height="wrap_con...
ViewPagerIndicator@Java//Set the pager with an adapterViewPager pager = (ViewPager)findViewById(R.id.pager);pager.setAdapt...
Activity LifeCycle
Activity LifeCyclepublic class Activity extends ApplicationContext {    protected void onCreate(Bundle savedInstanceState)...
Send Parameter●   BundleSendIntent data = new Intent("my.action");data.putExtra("point", point);data.putExtra("noqs", noqs...
Send ParameterParcelableprotected static class Foo implements Parcelable {  public static final Parcelable.Creator<Foo> CR...
Support multiple Screensres/layout/main.xml: single-pane layoutres/layout-large: multi-pane layoutres/layout-sw600dp: mult...
Do not use px ●   Use dp and sp<Button android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:...
Bitmap Sizes●   xhdpi: 2.0●   hdpi: 1.5●   mdpi: 1.0 (baseline)●   ldpi: 0.75
Bitmap ResourcesMyProject/ res/  drawable-xhdpi/        awesomeimage.png  drawable-hdpi/        awesomeimage.png  drawable...
UI Thread    ●   WTF is ANRWont Workhandler=new Handler();Runnable r=new Runnable(){        public void run()        {    ...
Android Threads@Overridepublicvoid onClick(View v){    my_button.setBackgroundResource(R.drawable.icon);    // SLEEP 2 SEC...
Android Threads@Overridepublicvoid onClick(View v){    my_button.setBackgroundResource(R.drawable.icon);    // SLEEP 2 SEC...
AsyncTaskprivate class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {    protected Long doInBackground(URL... u...
HTTP LibrariesYou can use Apache commonsOr I found these libraries wellhttp://loopj.com/android-async-http/AsyncHttpClient...
Push Notifications ●     Google Cloud Messaginghttp://developer.android.com/guide/google/gcm/index.html@manifest.xml<permi...
Push Notifications@javaGCMRegistrar.checkDevice(this);GCMRegistrar.checkManifest(this);final String regId = GCMRegistrar.g...
Dependency Injection ●   Roboguicehttp://code.google.com/p/roboguice/ ●   Guavahttp://code.google.com/p/guava-libraries/
WTF is DI    ●       Before DI                                       ●   After DIclass AndroidWay extends Activity {      ...
Image Caching ●   Google I/O 2012 app has a great image     caching libraryhttp://code.google.com/p/iosched/
Open Source apps ●   Google I/O 2012http://code.google.com/p/iosched/ ●   Github apphttps://github.com/github/android
ListViewMost important widgetFast ListView Tips ●   Inflate once ●   ViewHolder ●   Use Tag ●   Dont write a heavy code li...
Android Best Practices
Upcoming SlideShare
Loading in...5
×

Android Best Practices

9,515

Published on

Published in: Technology, News & Politics
0 Comments
14 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
9,515
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
156
Comments
0
Likes
14
Embeds 0
No embeds

No notes for slide

Transcript of "Android Best Practices"

  1. 1. ANDROIDDoes not Suck anymore!
  2. 2. Andy RubinNo plans to leave Google. Oh, and just formeme completeness -- there are over 900,000android devices activated each day :-)
  3. 3. Android evolves
  4. 4. Android Design Patternshttp://developer.android.com/design/index.html
  5. 5. No More Menu Button
  6. 6. New Buttons
  7. 7. Notifications
  8. 8. Navigation
  9. 9. ActionBar
  10. 10. Action Bar Selection
  11. 11. MultiPane
  12. 12. Dialogs
  13. 13. Android is not ios
  14. 14. IOS DesignIt was cool 2 years ago
  15. 15. Android is not ios
  16. 16. Fragmentation
  17. 17. Fragmentation
  18. 18. Fragmentation
  19. 19. Shut up and Show me Code Bitch!
  20. 20. Android Support Jar● V4 ● V13● Fragment ● FragmentCompat● FragmentManager ● FragmentPagerAdapter● FragmentTransaction ● FragmentStatePagerAdapter● ListFragment● DialogFragment● LoaderManager● Loader● AsyncTaskLoader● CursorLoader
  21. 21. Support JarJust change the import and use latest apis It rocks!!!
  22. 22. Fragment● Tablet and phone code comes together● One ring to rule them all!!!
  23. 23. FragmentDefine in XML<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" android:id="@+id/titles" android:layout_width="match_parent" android:layout_height="match_parent" /></FrameLayout>Set Content in codesetContentView(R.layout.fragment_layout);It works just like activitypublic static class TitlesFragment extends ListFragment {
  24. 24. Create FragmentDetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args);
  25. 25. Fire the fragment// Instantiate a new fragment. Fragment newFragment = CountingFragment.newInstance(mStackLevel); // Add the fragment to the activity, pushing this transaction // on to the back stack. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.simple_fragment, newFragment); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.addToBackStack(null); ft.commit();
  26. 26. Get the parameters@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { mLabel = args.getCharSequence("label", mLabel); } }
  27. 27. Use XMLAs much as you can
  28. 28. Inflate Views● Design using XML● And @javaView v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text);
  29. 29. DialogFragmentBetter Back button supportpublic static class MyDialogFragment extends DialogFragment {
  30. 30. Other Fragments● ListFragment● PreferenceFragment
  31. 31. Loaders● Loader Callback MethodsonCreateLoader()OnLoadFinished()onLoaderReset()
  32. 32. Great Man● Jack Whartonhttps://github.com/JakeWharton
  33. 33. Libraries● ActionBarSherlock● ActivityCompat2● NotificationCompat2● NineOldAndroids● SwipeToDismissNOA● Android-ViewPagerIndicator
  34. 34. ActionBarSherlock● At last you can use great ActionBar● Just usegetSupportActionBar()● Instead ofgetActionBar()
  35. 35. NineOldAndroids ● ObjectAnimator.ofFloat(myObject, "translationY", -myObject.getHeight()).start();AnimatorSet set = new AnimatorSet();set.playTogether( ObjectAnimator.ofFloat(myView, "rotationX", 0, 360), ObjectAnimator.ofFloat(myView, "rotationY", 0, 180), ObjectAnimator.ofFloat(myView, "rotation", 0, -90), ObjectAnimator.ofFloat(myView, "translationX", 0, 90), ObjectAnimator.ofFloat(myView, "translationY", 0, 90), ObjectAnimator.ofFloat(myView, "scaleX", 1, 1.5f), ObjectAnimator.ofFloat(myView, "scaleY", 1, 0.5f), ObjectAnimator.ofFloat(myView, "alpha", 1, 0.25f, 1));set.setDuration(5 * 1000).start();
  36. 36. ViewPagerIndicatorXML<com.viewpagerindicator.TitlePageIndicator android:id="@+id/titles" android:layout_height="wrap_content" android:layout_width="fill_parent" />
  37. 37. ViewPagerIndicator@Java//Set the pager with an adapterViewPager pager = (ViewPager)findViewById(R.id.pager);pager.setAdapter(new TestAdapter(getSupportFragmentManager()));//Bind the title indicator to the adapterTitlePageIndicator titleIndicator = (TitlePageIndicator)findViewById(R.id.titles);titleIndicator.setViewPager(pager);titleIndicator.setOnPageChangeListener(mPageChangeListener);
  38. 38. Activity LifeCycle
  39. 39. Activity LifeCyclepublic class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy();}
  40. 40. Send Parameter● BundleSendIntent data = new Intent("my.action");data.putExtra("point", point);data.putExtra("noqs", noqs);GetBundle b = getIntent().getExtras();noqs = b.getInt("noqs");point = b.getInt("point");
  41. 41. Send ParameterParcelableprotected static class Foo implements Parcelable { public static final Parcelable.Creator<Foo> CREATOR = new Parcelable.Creator<Foo>() { public Foo createFromParcel(Parcel source) { final Foo f = new Foo(); f.str = (String) source.readValue(Foo.class.getClassLoader()); return f; } public Foo[] newArray(int size) { throw new UnsupportedOperationException(); } };
  42. 42. Support multiple Screensres/layout/main.xml: single-pane layoutres/layout-large: multi-pane layoutres/layout-sw600dp: multi-pane layoutres/values/layouts.xmlres/values-sw600dp-land/layouts.xmlres/values-sw600dp-port/layouts.xmlres/values-large-land/layouts.xmlres/values-large-port/layouts.xml
  43. 43. Do not use px ● Use dp and sp<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/clickme" android:layout_marginTop="20dp" /><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20sp" />
  44. 44. Bitmap Sizes● xhdpi: 2.0● hdpi: 1.5● mdpi: 1.0 (baseline)● ldpi: 0.75
  45. 45. Bitmap ResourcesMyProject/ res/ drawable-xhdpi/ awesomeimage.png drawable-hdpi/ awesomeimage.png drawable-mdpi/ awesomeimage.png drawable-ldpi/ awesomeimage.png
  46. 46. UI Thread ● WTF is ANRWont Workhandler=new Handler();Runnable r=new Runnable(){ public void run() { tv.append("Hello World"); }};handler.postDelayed(r, 1000);
  47. 47. Android Threads@Overridepublicvoid onClick(View v){ my_button.setBackgroundResource(R.drawable.icon); // SLEEP 2 SECONDS HERE ... Handler handler =newHandler(); handler.postDelayed(newRunnable(){ publicvoid run(){ my_button.setBackgroundResource(R.drawable.defaultcard); } },2000);}
  48. 48. Android Threads@Overridepublicvoid onClick(View v){ my_button.setBackgroundResource(R.drawable.icon); // SLEEP 2 SECONDS HERE ... Handler handler =newHandler(); handler.postDelayed(newRunnable(){ publicvoid run(){ my_button.setBackgroundResource(R.drawable.defaultcard); } },2000);}
  49. 49. AsyncTaskprivate class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); }}new DownloadFilesTask().execute(url1, url2, url3);new DownloadFilesTask().execute(url1, url2, url3);
  50. 50. HTTP LibrariesYou can use Apache commonsOr I found these libraries wellhttp://loopj.com/android-async-http/AsyncHttpClient client = new AsyncHttpClient();client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { System.out.println(response); }});This works as wellhttp://code.google.com/p/android-query/
  51. 51. Push Notifications ● Google Cloud Messaginghttp://developer.android.com/guide/google/gcm/index.html@manifest.xml<permission android:name="my_app_package.permission.C2D_MESSAGE" android:protectionLevel="signature" /><uses-permission android:name="my_app_package.permission.C2D_MESSAGE" /><receiver android:name="com.google.android.gcm.GCMBroadcastReceiver"android:permission="com.google.android.c2dm.permission.SEND" >... <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="my_app_package" /> </intent-filter></receiver>
  52. 52. Push Notifications@javaGCMRegistrar.checkDevice(this);GCMRegistrar.checkManifest(this);final String regId = GCMRegistrar.getRegistrationId(this);Get regId and fire it from serverYou should use this library, all other are deprecated
  53. 53. Dependency Injection ● Roboguicehttp://code.google.com/p/roboguice/ ● Guavahttp://code.google.com/p/guava-libraries/
  54. 54. WTF is DI ● Before DI ● After DIclass AndroidWay extends Activity { class RoboWay extends RoboActivity { @InjectView(R.id.name) TextView TextView name; name; public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle super.onCreate(savedInstanceState); savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setContentView(R.layout.main); name = (TextView) findViewById(R.id.name); name.setText( "Hello, " + myName ); } }} }
  55. 55. Image Caching ● Google I/O 2012 app has a great image caching libraryhttp://code.google.com/p/iosched/
  56. 56. Open Source apps ● Google I/O 2012http://code.google.com/p/iosched/ ● Github apphttps://github.com/github/android
  57. 57. ListViewMost important widgetFast ListView Tips ● Inflate once ● ViewHolder ● Use Tag ● Dont write a heavy code like network operation in getView methodhttp://yekmer.posterous.com/fast-listview-scrolling-in-android
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×