Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ho Chi Minh.apk

jsugai
August 24, 2016

Ho Chi Minh.apk

Shibuya/Umeda .apk in Ho Chi Minh City

jsugai

August 24, 2016
Tweet

More Decks by jsugai

Other Decks in Programming

Transcript

  1. 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…
  2. 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)
  3. 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.
  4. 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
  5. 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.
  6. <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 :
  7. 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)
  8. 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.
  9. 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.
  10. Doze In Doze mode, the system attempts to conserve battery

    by restricting apps' access to network and CPU-intensive services.
  11. 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
  12. “A good architecture allows volatile decisions to be easily changed”

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

    no UI dependency • no Database dependency • does not depend of any external agency The idea is simple!
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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
  19. 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.
  20. 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
  21. Android MVVM MODEL Data: Models,DB a business logic ViewModel VIEW

    UI: Activity,Fragment Android Databinding or VM Class
  22. 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>
  23. 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); } }
  24. 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
  25. 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()
  26. 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
  27. 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()); }
  28. 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.
  29. 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.
  30. 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);
  31. 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
  32. 3"*-ࢦඪ • Response ͸ 100msະຬʹͳΔΑ͏ʹ • Animation ͸16msຖʹͳΔΑ͏ʹ • Idle

    ͸ 100msະຬʹͳΔΑ͏ʹ • Load͸ 1000msະຬʹऴΘΔΑ͏ʹ
  33. 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
  34. 24ms UPDATE UPDATE UPDATE UPDATE Draw! Draw! Draw! 16ms 16ms

    16ms UPDATE 24ms UPDATE Draw! Draw! 16ms 32ms dropped frame Best Perfomance Dropped Frame
  35. Other • Overdraw : use as few OverDraw as possible

    • CustomViewsɿonDraw optimization
  36. 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
  37. 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
  38. 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
  39. 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()
  40. Layout Optimization • Simple is Best • Shallow and Wide

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

    higher • small size(100KB) • automatically layout optimize …like storyboard
  42. 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
  43. UPDATE UPDATE UPDATE Draw! Draw! Draw! 16ms 16ms 16ms UPDATE

    Draw! Draw! 16ms 32ms dropped frame GC GC
  44. bad Heap Allocation pattern Loop [Alloc] - New Object/Class -

    Layout Inflate - Short Lifecycle Variable Alloc
  45. file format • PNG • JPG/GIF • WebP • VD(Vector

    Drawable) high frequency Recommendation
  46. 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
  47. 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
  48. 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.
  49. 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)
  50. • 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
  51. • 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