Pro Yearly is on sale from $80 to $50! »

Ho Chi Minh.apk

Cf72ecd4105b5818fcabcc0c0aaeee22?s=47 jsugai
August 24, 2016

Ho Chi Minh.apk

Shibuya/Umeda .apk in Ho Chi Minh City

Cf72ecd4105b5818fcabcc0c0aaeee22?s=128

jsugai

August 24, 2016
Tweet

Transcript

  1. )P$IJ.JOIBQL

  2. Agenda • Android 7.0 Nougat • Android Dev Architecture •

    Performance Optimization
  3. Android 7.0 Nougat features

  4. 08/22 2016 Release!

  5. 08/22 2016 Release! 250APIs

  6. Key Developer Features Multi-window Support,Notifications,JIT/AOT Compilation,Quick Path to App Install,Doze

    on the Go Background Optimizations,SurfaceView,Data Saver Vulkan API,Quick Settings Tile API,Number Blocking Call,Screening Locales and Languages,New Emojis,ICU4J APIs in Android,WebView,OpenGL ES 3.2 API, Android TV,Recording Android for Work,Accessibility,Direct Boot,Key Attestation,Network Security Config,Default Trusted CA,APK Signature Scheme v2,Scoped Directory Access,Keyboard Shortcuts Helper,Custom Pointer API,Sustained Performance API,VR Support,Print Service Enhancements,Virtual Files,FrameMetricsListener API too many…
  7. 1. Support MultiWindow 2. Notification 3. Background Optimization 4. Doze

    Optimization
  8. Support Multi-Window - MultiWindow is default enable - Split screen/Freeform

    mode - Support Drag and Drop
 (Activity to Activity) - Support Screen Rotate - Picture in Picture(TV only)
  9. AndroidManifest Set this attribute in your manifest's <activity> or <application>

    node to enable or disable multi-window display: android:resizeableActivity=["true" | "false"] If your app targets Android N, but you do not specify a value for this attribute, the attribute's value defaults to true.
  10. AndroidManifest Set this attribute in your manifest's <activity> node to

    indicate whether the activity supports picture-in-picture display. This attribute is ignored if android:resizeableActivity is false. android:supportPictureInPicture=["true" | "false"] ※ Android TV
  11. LayoutAttributes android:defaultWidth Default width of the activity when launched in

    freeform mode.
 android:defaultHeight Default height of the activity when launched in freeform mode.
 android:gravity Initial placement of the activity when launched in freeform mode. See the Gravity reference for suitable values.
 android:minHeight, android:minWidth Minimum height and minimum width for the activity in both split-screen and freeform modes.
  12. <activity android:name=“.HomeActivity”> <layout android:defaultHeight="500dp" android:defaultWidth="600dp" android:gravity="top|end" android:minHeight="450dp" android:minWidth="300dp" /> </activity>

    <activity android:name=“.HomeActivity” android:resizeableActivity=“false” …. > </activity> Enable Multi-Screen (Default Enable) : Disable Multi-Screen :
  13. User returns to the activity onNewIntent() onStateNotSaved() onRestart() Activity launched

    onCreate() onResume() onPostCreate() onPostResume() Activity Running onPause() onStop() onDestroy() onStart() onUserLeaveHint() onSaveInstanceState() Activity Shutdown Activity Shutdown User navigates to the activity User navigates to the activity Apps with higher priority need memory MultiWindow (unfrocks) &
 MultiWindow (focus)
  14. Notification - Direct Reply - Bundled Notifications

  15. Direct Reply // Key for the string that's delivered in

    the action's intent. private static final String KEY_TEXT_REPLY = "key_text_reply"; String replyLabel = getResources().getString(R.string.reply_label); RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(replyLabel).build(); Create instance of RemoteInputBuilder // Create the reply action and add the remote input. Notification.Action action = new Notification.Action.Builder(R.drawable.ic_reply_icon, getString(R.string.label), replyPendingIntent) .addRemoteInput(remoteInput) .build(); Attach the RemoteInput object to an action using addRemoteInput(). // Build the notification and add the action. Notification newMessageNotification = new Notification.Builder(mContext) .setSmallIcon(R.drawable.ic_message) .setContentTitle(getString(R.string.title)) .setContentText(getString(R.string.content)) .addAction(action)) .build(); // Issue the notification. NotificationManager notificationManager =NotificationManager.from(mContext); notificationManager.notify(notificationId, newMessageNotification); Apply the action to a notification and issue the notification.
  16. Bundle Notification - Notification Group - NotificationCompat.Builder#setGroup(String groupkey) Note: If

    the same app sends four or more notifications and does not specify a grouping, the system automatically groups them together.
  17. Background Optimization Please see the Section “Battery Optimization“

  18. Doze In Doze mode, the system attempts to conserve battery

    by restricting apps' access to network and CPU-intensive services.
  19. restrictions • Network access is suspended. • The system ignores

    wake locks. • Standard AlarmManager alarms are deferred to the next maintenance window.
 The system does not perform Wi-Fi scans. • The system does not allow sync adapters to run. • The system does not allow JobScheduler to run
  20. Doze Optimization Please see the Section “Battery Optimization“

  21. Android Architecture

  22. "Architecture is about Intent, not Frameworks" ΞʔΩςΫνϟͱ͸ʢྑ͍෺Λ࡞Γ͍ͨͱ͍͏ʣ ҙࢤɾҙਤͰ͋ΓɺϑϨʔϜϫʔΫͰ͸ͳ͍ Martin Fowler

  23. “A good architecture allows volatile decisions to be easily changed”

    l༏ΕͨΞʔΩςΫνϟͱ͸
 ʮ؆୯ͳมߋ͕΋ͨΒ͢ෆ҆ఆ͞ʯ
 Λڐ༰Ͱ͖ΔϞϊͰ͋Δz Robert C Martin
  24. “Android Clean Architecture”

  25. Android Clean Architecture • no Framework dependency • Testable. •

    no UI dependency • no Database dependency • does not depend of any external agency The idea is simple!
  26. Android Clean Architecture It is not a must to use

    only 4 circles (as you can see in the picture), because they are only schematic but you should take into consideration the Dependency Rule: source code dependencies can only point inwards and nothing in an inner circle can know anything at all about something in an outer circle.
  27. Android Clean Architecture The objective is the separation of concerns

    by keeping the business rules not knowing anything at all about the outside world, thus, they can can be tested without any dependency to any external element.
  28. Presentation Layer Is here, where the logic related with views

    and animations happens. It uses no more than a Model View Presenter (MVP from now on), but you can use any other pattern like MVC or MVVM. I will not get into details on it, but here fragments and activities are only views, there is no logic inside them other than UI logic, and this is where all the rendering stuff takes place.
  29. Domain Layer Business rules here: all the logic happens in

    this layer. Regarding the android project, you will see all the interactors (use cases) implementations here as well. This layer is a pure java module without any android dependencies. All the external components use interfaces when connecting to the business objects.
  30. Data Layer All data needed for the application comes from

    this layer through a UserRepository implementation (the interface is in the domain layer) that uses a Repository Pattern with a strategy that, through a factory, picks different data sources depending on certain conditions. For instance, when getting a user by id, the disk cache data source will be selected if the user already exists in cache, otherwise the cloud will be queried to retrieve the data and later save it to the disk cache. The idea behind all this is that the data origin is transparent for the client, which does
  31. Android MVP MODEL Data: Models,DB a business logic PRESENTER Mediator

    VIEW UI: Activity,Fragment
  32. MVP Layer

  33. Frameworks and Driver Interface Adapters Application Business Rules Enterprise Business

    Rules
  34. None
  35. Sample public interface Presenter<T extends View> { void onCreate(); void

    onStart(); void onStop(); void onPause(); void attachView(T view); } Every presenter class should implement following interface.
  36. public class CalendarsPresenter implements Presenter<CalendarsView> { …. // fetch Usecase

    to Presenter public CalendarsPresenter(FetchCalendarsUsecase fetchCalendarsUsecase) { this.fetchCalendarsUsecase = fetchCalendarsUsecase; } @Override public void onStop() { if (getCalendarsSubscription != null && !getCalendarsSubscription.isUnsubscribed()) { getCalendarsSubscription.unsubscribe(); } } @Override public void attachView(CalendarsView view) { this.calendarsView = view; getCalendars(); } private void getCalendars() { calendarsView.showLoading(); getCalendarsSubscription = fetchCalendarsUsecase.execute() … showView().showCalenders(); } ... } Implements Presenter
  37. Android MVVM MODEL Data: Models,DB a business logic ViewModel VIEW

    UI: Activity,Fragment Android Databinding or VM Class
  38. DataBinding Layout <layout> <data> <variable name="user" type="com.android.example.User"/> </data> <LinearLayout …>

    <TextView android:text="@{user.name}"/> <TextView android:text=“@{user.lastName}"/> </LinearLayout> </layout>
  39. Class public class User { public final String firstName; public

    final String lastName; public final int age; public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } } Implementation Code public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_m User user = new User("Hao", "Hao"); binding.setUser(user); } }
  40. 1. Choose (Software)Design and Architecture Pattern
 - MVC,MVP,MVVM 2. Architecture

    Optimize 3. Good Design Principle 4. Use OSS
 - ButterKnife, Dagger(DI framework)
 - Retrofit
 - okHttp3
 - Reactive Extensions(Rx) 5. Use Framework
 - Support Library/Design Support Library
 - Google APIs
 - etc
  41. Dagger & Butter Knife Dagger
 A fast dependency injector for

    Android and Java Butter Knife
 Field and method binding for Android views http://goo.gl/qTv6Ul http://goo.gl/hH2jyX Goodby! findViewbyId()
  42. Retrofit Retrofit turns your REST API into a Java interface.

    
 http://square.github.io/retrofit/
 Retrofit has been able to fulfill every networking demand that I’ve thrown at it. 
 It’s a breeze to add headers, use your own JSON marshaller (GSON is built in), or even pass in your own network client. RxJava support was recently added as well (can return Observables instead of scalar values). Check out how little you need to get started: //Create a Model that represents your JSON data (It’s ok if fields are missing that are present in JSON) public class User { public String avatar_url; public String login; } //Create an interface public interface Github { @GET(“/search/users”) UserResponse users(@Query(“q”) String name); } //Auto Generate implementation from Interface Github api = new RestAdapter.Builder() .setEndpoint(“https://api.github.com") .build() .create(Github.class) // user your endpoint UserResponse response =api.users(request.getName()); https://goo.gl/TXhwKH
  43. Retrofit + RxJava https://goo.gl/TXhwKH github.users(“Mike”) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .Subscribe(user->doSomethingWithResponse(user), throwable ->doSomethingWithError(throwable))

    Observable Implementation
  44. okHttp An HTTP & HTTP/2 client for Android and Java

    applications. https://goo.gl/NN87QC private static final String IMGUR_CLIENT_ID = "..."; private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("title", "Square Logo") .addFormDataPart("image", "logo-square.png", RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png"))) .build(); Request request = new Request.Builder() .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID) .url("https://api.imgur.com/3/image") .post(requestBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
  45. ReactiveX An API for asynchronous programming with observable streams RxJava

    RxJava is a Java VM implementation of ReactiveX a library for composing asynchronous and event-based programs by using observable sequences.
  46. @see RxJava StepbyStep

  47. Android Support Library • Backward-compatible versions of framework components. •

    UI elements to implement the recommended Android layout patterns. • Support for different form factors. • Miscellaneous utility functions.
  48. Android Support Library RecyclerView CardView NavigationDrawer

  49. CoordinatorLayout

  50. Google APIs GcmNetworkManager You can use the API to schedule

    network-oriented tasks, and let Google Play services batch network operations across the system. This greatly simplifies the implementation of common patterns, such as waiting for network connectivity, network retries, and back-off. https://goo.gl/Hpf1gV // Schedule a task to occur between five and fifteen minutes from now: OneoffTask myTask = new OneoffTask.Builder() .setService(MyGcmTaskService.class) .setExecutionWindow( 5 * DateUtil.MINUTE_IN_SECONDS, 15 * DateUtil.MINUTE_IN_SECONDS) .setTag("test-upload") .build(); GcmNetworkManager.getInstance(this).schedule(myTask);
  51. App Optimization

  52. Essential Tips To Android’s Performance

  53. Performance?

  54. 0.1sec 1sec 10sec 60FPS

  55. 1.0.1 sec is about the limit for having the user

    feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result. 2. 1.0 sec is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. 
 3. 10 sec is about the limit for keeping the user's attention focused on the dialogue.
 4. 60 FPS is most people won’t perceive much smoother images above 60 fps. Response Times: The 3 Important Limits The Illusion of Motion
  56. RAIL https://goo.gl/sAzRm8

  57. 3"*-ࢦඪ • Response ͸ 100msະຬʹͳΔΑ͏ʹ • Animation ͸16msຖʹͳΔΑ͏ʹ • Idle

    ͸ 100msະຬʹͳΔΑ͏ʹ • Load͸ 1000msະຬʹऴΘΔΑ͏ʹ
  58. Response : 100ms Animation : 16ms Load : 1000ms RAIL

    : Android
  59. Load : 1000ms Action : 100ms Action : 100ms Anim

    : 16ms Anim : 16ms Real-Time (Human) Time Perception feeling good feeling good feeling good USABILITY Touch/Drag Touch/Drag
  60. Animation : 16ms UP Down TAB NavigationDrawer Right Left Scroll

  61. Rendering Web Android Draw Layout Measure Composite Paint Layout Style

    JavaScript
  62. 24ms UPDATE UPDATE UPDATE UPDATE Draw! Draw! Draw! 16ms 16ms

    16ms UPDATE 24ms UPDATE Draw! Draw! 16ms 32ms dropped frame Best Perfomance Dropped Frame
  63. Now Loading… launch Splash screen Home Screen 1000ms 1000ms Loading

    : 1000ms ???ms
  64. Other • Overdraw : use as few OverDraw as possible

    • CustomViewsɿonDraw optimization
  65. How can I profile Android app?

  66. Android LINT

  67. StrictMode IllegalState Best Practice Compile Time Runtime Compilation Time Android

    Lint Runtime Exception Strict Mode Thread Policy : That would help to detect if our code have some slow operation VM Policy : detect vulnerability problem, code have memory leak operation
  68. TraceView

  69. TraceView Click Invocation Count : How many times the method

    was called. Inclusive time : Time spent in the method and all of its children Exclusive time : Time spent just in the method
  70. dumpsys $ adb shell dumpsys meminfo com.example.android.apis:empty ** MEMINFO in

    pid 10172 [com.example.android.apis:empty] ** Pss Pss Shared Private Shared Private Heap Heap Heap Total Clean Dirty Dirty Clean Clean Size Alloc Free ------ ------ ------ ------ ------ ------ ------ ------ ------ Native Heap 0 0 0 0 0 0 1864 1800 63 Dalvik Heap 764 0 5228 316 0 0 5584 5499 85 Dalvik Other 619 0 3784 448 0 0 Stack 28 0 8 28 0 0 Other dev 4 0 12 0 0 4 .so mmap 287 0 2840 212 972 0 .apk mmap 54 0 0 0 136 0 .dex mmap 250 148 0 0 3704 148 Other mmap 8 0 8 8 20 0 Unknown 403 0 600 380 0 0 TOTAL 2417 148 12480 1392 4832 152 7448 7299 148
  71. Layout Optimization

  72. Android View Layout Process Draw Layout Measure 1st Pass :

    Measure Pass How Android Draws Views https://goo.gl/mo30En 2nd Pass : Layout Pass onMeasure() onMeasure() onMeasure() onMeasure() onMeasure() Root node onLayout() onLayout() onLayout() onLayout() onLayout() Root node onDraw() invalidate() / requestLayout()
  73. Nest [SHALLOW] [DEEP] [Complex] [Simple] Layout res/xxxx_layout.xml ᶃ ᶄ ᶅ

    Bad Good
  74. OverDraw 1x Overdraw 2x Overdraw 3x Overdraw 4x Overdraw

  75. Layout Optimization • Simple is Best • Shallow and Wide

    > Deep and narrow
 • Use Support Lib/DSL • Design Guideline • CoordinatorLayout • Navigation Drawer • Powerful Layout • ConstraintLayout • FlexboxLayout
  76. ConstraintLayout • API Level9 and higher • AS 2.2 and

    higher • small size(100KB) • automatically layout optimize …like storyboard
  77. FlexboxLayout • The similar capabilities of CSS Flexible Box Layout

    Module to Android • LinearLayout + GridLayout + α • layout dynamically • (Automatically) wrap/(unwrap) attribute https://goo.gl/6RMi4K github.com/google/flexbox-layout
  78. HierarchyViewer

  79. Heap Optimization

  80. GC Event GC Event memory
 threshold Allocated
 heap

  81. UPDATE UPDATE UPDATE Draw! Draw! Draw! 16ms 16ms 16ms UPDATE

    Draw! Draw! 16ms 32ms dropped frame GC GC
  82. Minor/Scavenge GC UPDATE Draw! Draw! GC GC Scavenge GC

  83. Full GC UPDATE Draw! Draw! GC GC Full GC

  84. bad Heap Allocation pattern Loop [Alloc] - New Object/Class -

    Layout Inflate - Short Lifecycle Variable Alloc
  85. LeakCanary A memory leak detection library for Android and Java.

    https://goo.gl/YNEK2A
  86. Image resource optimization

  87. file format • PNG • JPG/GIF • WebP • VD(Vector

    Drawable) high frequency Recommendation
  88. Can the image be a VD? Do you support WebP?

    Does it need transparency? VD WebP PNG JPG Is it simple or complex? Use a tool Reduce Colors Hand Optimize Image compression for Android developers
  89. WebP : Photoshop Plugin https://developers.google.com/speed/webp/docs/compression http://telegraphics.com.au/sw/product/WebPFormat#webpformat ↑Download

  90. WebP : Sketch + cwebp/gif2webp https://developers.google.com/speed/webp/docs/compression Sketch GitHub PNG WebP

  91. Android LINT

  92. Detect Unused Resource LINT -> Performance -> Inspect Code… ->

    “Unused Resources”
  93. Battery Optimization

  94. Do you know what this is?

  95. 30:70

  96. Battery Drain 25%~30% Core/Function 70%~75% Analytics, Location, Ads 50%~ Core/Function

    ~50% Analytics, Location, Ads Ideal Real FROM: New tool reduces smartphone battery drain by intelligently suppressing background activities [Background Process] http://goo.gl/fyICpK
  97. What about the other side?

  98. What was the cause? SDKs: Analytics, Location, Ads

  99. visualize

  100. Battery Historian https://goo.gl/sf1Brr

  101. Restrictions on CONNECTIVITY_ACTION • Android 7.0 Nougat • Background process(App)

    is do not receive to CONNECTIVITY_ACTION
 • Foreground App only
 • Apps cannot send or receive ACTION_NEW_PICTURE or ACTION_NEW_VIDEO broadcasts.
  102. Optimization • Scheduling Jobs API • ʢAPI Lv21 or higherʣuse

    JobScheduler API • ʢAPI Lv20 or underʣ use GcmNetworkManager API • Picture or Video • JobInfo.Builder#addTriggerContentUri(JobInfo.TriggerContentUri)
  103. Optimizing for Doze and App Standby https://goo.gl/Zglj4J

  104. Documents

  105. • The RAIL Performance Model
 https://goo.gl/0CjvsJ • Image Compression for

    Android Developers
 https://goo.gl/V95BJg • Best Practices for Performance
 https://goo.gl/8qeKb7 • Optimize Your App
 https://goo.gl/e2oKYK • Principles of Mobile App Design: Engage Users and Drive Conversions
 https://goo.gl/LUCZZG
  106. • New tool reduces smartphone battery drain by intelligently suppressing

    background activities
 http://goo.gl/zWNEaL • Best Practices for Background Jobs
 https://goo.gl/u6NYhX • Performance RAIL's
 https://goo.gl/QePFd8 • Response Time: The 3 Important Limits
 https://goo.gl/hpm3yj • The Illusion of Motion
 https://goo.gl/tMspjz