New API in Android O

This presentation is based on Google I/O 2017 , I will try to extend and look in deep most interesting coming features discussed during this event , 
As this topic may be long and extended , Every week I update this document with more subjects and details , I start this week by a few features.

No Casting required for findViewById() anymore :
We all are tired of casting return view each time we call findViewById()!

TextView  tv = (TextView)findViewById(R.id.tvText); => Casting Required
Button btn = (Button)findViewById(R.id.btn); => Casting Required

So good news with Android O is ,  it’s over , and we can do:

TextView  tv = findViewById(R.id.tvText); => Casting NOT Required
 Button btn = findViewById(R.id.btn); => Casting NOT Required


PIP (Picture In Picture) mode:
This is a new feature introduced in Android O , new feature , If you apply PIP mode to your , 
It becomes an overlay small window in one corner of your screen while you are navigating to 
other Activityies .Thie feature exists already in Android TV or other applications supporting 
Chromcast feature for  video player such as Youtube , If Youtube is streaming contents to 
a Google Chromcast device , Youtube put your playing video in a small window in bottom corner.


<activity android:name=".MainActivity"

  👉 android:supportsPictureInPicture="true" //don’t need android:resizeableActivity anymore

     android:configChanges=" screenSize|smallestScreenSize|screenLayout|orientation" >

</activity>


Notice: configChanges attributes override the default android behaviour which is to restart Activity after a change in orientation, by setting android:configChanges="xxxx" 
you prevent destruction and restarting Activity , instead  onConfigurationChanged()
is called and you can take actions inside it.


Improvement in MediaPlayer :

There are a very interesting API added to android.media.MediaPlayer

PersistableBundle getMetrics () 

This method return you information about Codec , duration, Bitrate , 
etc You can uses constants MediaPlayer.MetricsConstants to retrieve 
information you need  for example:

MediaPlayer mediaPlayer = new MediaPlayer();
PersistableBundle metrics = mediaPlayer.getMetrics();
 => API //26 introduced with Android O
String audioCodec = metrics.get(MediaPlayer.MetricsConstants.CODEC_AUDIO); 
long duration  = metrics.get(MediaPlayer.MetricsConstants.DURATION);


seekTo API improved in Android O
We previously used seekTo api as prototype seekTo(int mSec) , which mSec is offset in mili seconds , now a new API is added with this prototype seekTo(int mSec, int mode)  , for example you can find closest time offset to your frame when calling seekTo(x, SEEK_CLOSEST_SYNC) => Closest Frame to X mSec


Notice : If you set mode = SEEK_PREVIOUS_SYNC , it becomes the previous api seekTo(int)


Font management in Android O :
In Android O , Fonts are now supported in res hierarchy  and accessible by R.font.font_name ,The same way we define drawable or strings group , It’s also possible to define a group of fonts for maultiple use cases :



Good news:
This feature is also supported and bring to developers by Google  Support Libraries V26 , no need anymore to use third party librarie such as Calligraphy .With new Support Library updated you can take benefits to this feature.


AccessibilityService utilities:

There is a significant improvement in AccessibilityService ,some common setting is moved to App level to avoid impacting rest of Apps.

Example 
An application that sets an Alarm or produce sound in some way needs to set volume of speaker in
a few limited mode (System,Media, Ringing ,…..) , in this case when App modify volum this change is at device level not App level, so It impacts all applications , this is a very frustrated user experience ,
 in Android O , you can set sounds attributes at App level , once you exit , default values are restored

Change In Architecture:

The most exciting annonce Google made in I/O 2017 is the introduction of Architecture Library(android.arch.lifecycle.LifecycleActivity),The Architecture Library introduce some components to optimize the current Life cycle of application components (Activity , Service,..) among them 
LifeCycleActivity.LifeCycleActivity is extended from FragmentActivity , so any activity based on 
AppComaptActivity or FragmentActivity can use it .Here the main purpose of introduction of such a
an Activity is to design a pattern of  Observer and LifeCycle owner , Android team recommend to 
use Observers in order to delegate all Life Cycle related to Activity to a ViewModel class 
and that class by interaction with LifeCycleActivity an will be in charge of Activity life cycle handling.

Android platform team have made good things to manage life cycle of Activity , FragmentActivity,…in a easier way in order to avoid all boiler plate coding we usually add to onStart,onStop,onResume,onDestroy to care of our objects be synchronized to Activity or Fragment life cycle.There is new Data typeintroduced named “LiveData” which prototype is 
LiveData<T>  => one of the characteristic of this class is LifeCycle aware , let’s see a concrete example :


Retain data in configuration change : Suppose in your Activity you call a web service to get data back 

public class MyActivity extends AppCompatActivity {   

UserInfo userInfo;

@Override    
 protected void onCreate(Bundle savedInstanceState) {  
       super.onCreate(savedInstanceState);   
      setContentView(R.layout.activity_my);    
     userInfo = networkService.getUserInfo(userId); 
    }

 

suddenly orientation changes what happens? Yep onCreate is called again then  your networkService should fetch data again!
Solution with new Architecture Component:

First We create a ViewModel subclass :

class MyActivityViewModel extends ViewModel{ 

            private LiveData<UserInfo> liveData;   
           public LiveData getUserInfo(int userId){    
            if(liveData == null){        
         liveData = networkService.getUserInfo(userId); =>
 Run web service repeatedly after a config  change //such as orientation.   

            }        

           return liveData;       }}

 

then in your Activity:

public class MyActivity extends AppCompatActivity {    

@Override    protected void onCreate(Bundle savedInstanceState) {   
     super.onCreate(savedInstanceState);  
      setContentView(R.layout.activity_my);    
    ViewModelProviders.of(this) => 
Component Library introduced with Android O will retain data during config //change.
            .get(MyActivityViewModel.class)  
              .getUserInfo(userId)    
            .observe(this , callback{     
       //UI update        });


    }

 

IMPORTANT : android.arch.lifecycle.LifecycleActivity (Alpha component Library) is still an alpha library

 (https://developer.android.com/topic/libraries/architecture/adding-components.html)



May 29 , 2017

Khosrov 

 

 © Xosrov 2016