Android developers recommended Android developers need the necessary skills
Android 8.0 Oreo is smarter, faster, and more powerful. It’s not just cookies the world loves, it’s a new Android system for you. Android 8.0 introduces a variety of new features for both users and developers. This article highlights new features for developers. Be sure to check out Android 8.0 behavior changes to see where platform changes may affect your application. Reading through this article, you will learn the following:
- New StrictMode check procedure
- Cache data
- Content providers are paginated
- Content refresh request
- JobScheduler improvement
- Custom data stores
- FindViewById () signs changes
- Media enhancement
- MediaPlayer
- Audio playback control
- Enhanced media file access
- Custom document providers
- The connection
- Shared
- Smart text selection
- Accessibility function
- Independent volume adjustment
- Fingerprint gestures
- Word level highlights
- Standardize single-ended range values
- Tooltip text
- Security and Privacy
- New account access and Discovery API
- Google Safe Browsing API
- test
- Runtime and tools
- Android enterprise edition
1. New StrictMode test procedure
Android 8.0 has added three new StrictMode checkers to help identify possible errors in the application:
detectUnbufferedIo()
Detects when your application reads or writes unbuffered data, which can have a significant impact on performance.detectContentUriWithoutPermission()
Will detect when your application accidentally forgets to grant permissions to other applications when it starts the Activity outside of itself.detectUntaggedSockets()
Will detect when your application is using network traffic and notsetThreadStatsTag(int)
Use traffic markers for debugging purposes.
2. Cache data
Android 8.0 optimizes the navigation and behavior of cached data. Each application now gets a quota of disk space to store cached data returned by getCacheQuotaBytes(UUID).
When the system needs to release disk space, it starts to delete cache files from the applications that exceed the maximum quota. Therefore, if you always keep your cache data below the quota level, your cache files will last out when you have to purge some files from the system. When deciding which cache files to delete in your application, the system will first consider removing the oldest files (determined by modification time).
You can also enable two new behaviors per directory to control how the system frees cached data:
StorageManager.setCacheBehaviorAtomic()
Can be used to indicate that a directory and all its contents should be deleted as an indivisible whole.setCacheBehaviorTombstone(File, boolean)
Can be used to indicate that files in a directory should not be deleted, but should be truncated to 0 bytes, leaving empty files intact. Finally, when you need to allocate disk space for large files, consider using a new oneallocateBytes(FileDescriptor, long) API
, it will automatically clear the cache files that belong to other applications (as needed) to satisfy your request. Call when determining whether the device has enough disk space to store your new datagetAllocatableBytes(UUID)
Don’t usegetUsableSpace()
Because the former takes into account any cached data that the system wants to clear for you.
3. Content provider pagination
We have updated the content provider to support loading large datasets, one page at a time. For example, a photo application with a large number of images can query a subset of the data to be displayed on the page. Each result page returned by the content provider is represented by a Cursor object. Clients and providers must implement paging to take advantage of this feature.
For more information about ContentProvider changes, see ContentProvider and ContentProviderClient.
#4. Content refresh request
Now, both the ContentProvider and ContentResolver classes include the Refresh () function, which makes it easier for clients to know if the requested information is up to date.
You can extend the ContentProvider to add custom content refresh logic. Be sure to override the refresh() function to return true, telling the provider’s client that you tried to refresh the data yourself.
Your client application can explicitly request the refreshed content by calling another function, also called refresh(). When this function is called, the URI of the data to be refreshed is passed in.
Note: Because you may be constantly requesting data over the network, you should only call Refresh () from the client when there is a clear indication that the content is actually out of time. The most common reason to perform this type of content refresh is in response to the swipe refresh gesture, which explicitly requests that the current screen display the latest content.
5. JobScheduler improvement
Android 8.0 introduces several improvements to JobScheduler. Because you can often use scheduled jobs instead of currently limited background services or implicit broadcast receivers, these improvements make it easier for your applications to comply with the new background execution limits.
JobScheduler updates include:
- You can now associate work queues with scheduled jobs. To add a work item to the queue of a job, call
JobScheduler.enqueue()
. As the job runs, it can strip pending work from the queue and process it. This capability can handle the need to start a background service before (especially implementation)IntentService
Service). - You can now call
JobInfo.Builder.setClipData()
The way toClipData
Associated with the job. With this option, you can grant URI permissions associated with the job, similar to those permissions passed toContext.startService()
The way. You can also grant URI permissions to those used on the work queueintent
. - Scheduled jobs now support multiple new constraints:
JobInfo.isRequireStorageNotLow()
If the available storage space on the device is very low, the job will not run.JobInfo.isRequireBatteryNotLow()
If the battery level is at or below the critical threshold, the job will not run; The critical threshold indicates the amount of power in the Low Battery Warning dialog box displayed on the device.NETWORK_TYPE_METERED
Jobs require a pay-as-you-go network connection, such as most mobile data network data plans.
6. Customize data stores
Android 8.0 allows you to provide custom data stores for the top options, which can be useful if your application stores preferences in the cloud or in a local database, or if preferences are specific to a device. For more information about implementing data stores, see Customizing Data Stores.
7. FindViewById () signature changes
Now, all instances of the findViewById() function return
T instead of View. This change has the following effects:
- For example, if
someMethod(View)
和someMethod(TextView)
All calls acceptedfindViewById()
, which can cause the return type of existing code to be uncertain. - In the Java 8 source language, this is required when the return type is not restricted (for example,
assertNotNull(findViewById(...) ). SomeViewMethod ()))
Explicitly convert to View. - Rewrite not final
findViewById()
Functions (for example, activity.findViewById ()) will need to update their return type.
8. Media enhancements
There’s a new VolumeShaper class. You can use it to perform short automatic volume transitions, such as fade-in, fade-out, and cross-fade-out.
Audio focus enhancement
Audio applications share audio output on devices by requesting and discarding audio focus. The application handles changes in focus by starting or stopping playback or by evading volume. There’s a new AudioFocusRequest class. For this, the app uses new features to handle audio focus changes: auto dodge and delayed focus.
Index of the media
The new getMetrics() function returns a PersistableBundle object containing configuration and performance information, represented by a map of properties and values. Define the getMetrics() function for the following media classes:
- MediaPlayer.getMetrics()
- MediaRecorder.getMetrics()
- MediaCodec.getMetrics()
- MediaExtractor.getMetrics()
Metrics are collected separately for each instance and continue until the end of the instance’s life cycle. If no metrics are available, this function returns NULL. The actual metric returned depends on the class.
9 . MediaPlayer
Android 8.0 adds a variety of new functions to the MediaPlayer class. These functions can enhance your application’s ability to handle media playback in several ways:
Fine control when searching for frames. The ability to play drM-protected material. MediaPlayer now supports sample-level encryption.
Audio recorder
Audio recorders now support the MPEG2_TS format useful for streaming:
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
Please refer to the MediaRecorder. OutputFormat
-
MediaMuxer can now handle any number of audio and video streams, rather than just one audio track and/or one video track. Use addTrack() to remix as many tracks as you want.
-
MediaMuxer can also add one or more metadata tracks that contain user-defined information for each frame. The format of the metadata is defined by your application. Metadata tracks are supported for MP4 containers only. Metadata can be used for offline processing. For example, the sensor’s gyroscopic signal can be used to perform video stabilization operations.
When adding metadata tracks, the MIME format of the tracks must begin with the prefix “application/”. Writing metadata is the same as writing video/audio data, except that the data is not from MediaCodec. Instead, the application passes a ByteBuffer containing the associated timestamp to the writeSampleData() function. The timestamp must be in the same time base as the video and audio tracks.
The resulting MP4 file uses TextMetaDataSampleEntry, defined in section 12.3.3.2 of ISOBMFF, to indicate the MIME format of the metadata. When a file containing the metadata track is extracted using MediaExtractor, the MIME format of the metadata is extracted into MediaFormat ‘.
10. Audio playback control
Android 8.0 allows you to query and request how your device generates sound. The following controls for audio playback will make it easier for your service to produce sound only under favorable device conditions.
The AudioAttributes class contains a new sound type, USAGE_ASSISTANT, that corresponds to Google Smart Assistant’s answers on the device.
Device audio playback changes
If you want to own the service only in a specific device audio configuration is active when began to generate sound, you can use the AudioManager class registered a AudioManager. AudioPlaybackCallback instance, The latter’s onPlaybackConfigChanged() function helps you determine the currently active audio attribute set.
Explicitly request audio focus
Your service can submit a more refined device-level audio focus receive request using the requestAudioFocus() function. Introduced into a AudioFocusRequest object, you can use AudioFocusRequest. Builder to create the object. In this build class, you can specify the following options:
- The type of focus you want, for example
AUDIOFOCUS_GAIN_TRANSIENT or AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
. - When another audio service gains device focus, should your service continue in a quieter manner, or pause altogether.
- Can your service wait to get focus until the device is ready.
Note: Build your AudioFocusRequest instance, if you by calling setAcceptsDelayedFocusGain () indicates the service can wait for you to produce sound, you must also call setOnAudioFocusChangeListener (), So that your service knows when it can start producing sound.
11. Enhanced media file access
The Storage Access Framework (SAF) allows applications to display custom DocumentsProviders that give other applications access to files in a data source. In fact, document providers can even provide access to files that reside in network storage or use protocols such as media Transfer Protocol (MTP).
However, accessing large media files in remote data sources presents some challenges:
-
The media player needs to address the files from the document provider. When a large media file resides on a remote data source, the document provider must extract all the data beforehand and create snapshot file descriptors. The media player cannot play a file without a file descriptor, so it cannot start playing until the document provider finishes downloading the file.
-
Media collection managers such as photos apps must traverse a series of access URIs through the scope folder to access media stored on an external SD card. This access mode makes bulk operations on media, such as move, copy, and delete, very slow.
-
The media collection manager cannot determine the location of a document based on its URI. This makes it difficult for these types of applications to allow users to choose where to save media files. Android 8.0 addresses various challenges by improving the storage access framework.
##12. Custom document providers
Starting with Android 8.0, the Storage Access framework allows custom document providers to create addressable file descriptors for files residing in remote data sources. SAF can open a file and get a natively addressable file descriptor. The SAF then submits a discrete byte request to the document provider. This feature allows the document provider to return the exact byte range requested by the media player application without having to cache the entire file beforehand.
To use this feature, you need to call the new StorageManager. OpenProxyFileDescriptor () function. OpenProxyFileDescriptor ProxyFileDescriptorCallback object () function is acceptable as a callback. SAF invokes the callback any time a client application performs a file operation on a file descriptor returned by the document provider.
Direct document access
Starting with Android 8.0, you can use the getDocumentUri() function to get a URI that references the same document as a given mediaUri. However, because the returned URI is supported by the DocumentsProvider, the media collection manager can access the document directly without traversing the scoped directory tree. As a result, the media manager can perform file operations on documents at a significantly faster rate.
Note: The getDocumentUri() function can only locate media files; The application cannot be granted access to these files. For details on how to obtain access to media files, see the Reference documentation.
Document path
When using the storage Access framework in Android 8.0, you can use the findDocumentPath() function (present in the DocumentsContract and DocumentsProvider classes) to determine the path from the root of the file system based on the document ID. This function returns the Path in the documentsContract. Path object. If the file system has more than one defined path for the same document, this function returns the path most commonly used to access a document with a given ID.
This feature is particularly useful in the following situations:
-
Your application uses the Save as dialog box that shows specific document locations.
-
Your application displays folders in the search results view and if the user selects a folder, the application must load subdocuments within that particular folder.
Note: If your application only has access to certain documents in the path, the return value of findDocumentPath() will contain only folders and documents that your application can access.
13. The connection
WLAN perception
Android 8.0 has added support for WLAN awareness, which is based on the Peripheral-aware Networking (NAN) specification. On a wLAN-aware device, applications and nearby devices can search for and communicate with each other using a WLAN without relying on the Internet access point. We are working with hardware partners to bring WLAN-aware technology to devices as soon as possible. For information on how to integrate WLAN Awareness into your application, see WLAN Awareness.
bluetooth
Android 8.0 enhances bluetooth support by adding the following features:
Support AVRCP 1.4 standard, which supports music library browsing. Support bluetooth Low Power (BLE) 5.0 standard. Integrate the Sony LDAC codec into a Bluetooth stack.
Matching equipment
Android 8.0 provides apis that allow you to customize the pairing request dialog box when trying to pair with a companion device over Bluetooth, BLE, and WLAN. For more information, see Matching devices.
For more information on using Bluetooth on Android, see the Bluetooth Guide. For Android 8.0-specific changes to Bluetooth, see the Bluetooth section of the Android 8.0 Behavior Change page.
# 14. Sharing
Intelligence sharing
Android 8.0 understands users’ personalized sharing preferences and has a better handle on which apps to share different types of content. For example, if a user takes a picture of a receipt, Android 8.0 can suggest an expense-tracking app; A social media app can handle images better if users take selfies. Android 8.0 can automatically learn all of these modes based on the user’s personalized preferences.
Intelligent sharing applies to content types other than image, such as audio, video, text and URL.
To enable smart sharing, add an ArrayList with up to three string annotations to the intent to share content. These comments should describe the main parts or topics in the content. The following code example shows how to add a comment to an Intent:
ArrayList<String> annotations = new ArrayList<>();
annotations.add("topic1");
annotations.add("topic2");
annotations.add("topic3");
intent.putStringArrayListExtra(
Intent.EXTRA_CONTENT_ANNOTATIONS,
annotations
);
Copy the code
For more information about smart sharing annotations, see EXTRA_CONTENT_ANNOTATIONS.
15. Smart text selection
On compatible devices, Android 8.0 lets apps help users interact with text in a more meaningful way. When a user holds down a word in an entity in a recognizable format, such as an address or the name of a restaurant, the entire entity is selected. The user is presented with a floating toolbar containing applications that can work with the selected text entities. For example, if the system recognizes an address, it can direct the user to a map application.
The entities identified by the system include addresses, Web addresses, phone numbers, and E-mail addresses. For more information, see TextClassifier.
Android 8.0 allows developers to create their own accessibility services using the following accessibility features. For more information on how to make your application more accessible, see Accessibility features.
Barrier-free button
Your accessibility service can now request that a accessibility button be displayed in the navigation area of the system, which allows users to quickly activate your service functionality from any location on their device. To do this, please at some object AccessibilityServiceInfo android: add FLAG_REQUEST_ACCESSIBILITY_BUTTON logo accessibilityFlags attributes. Later, you can use the registerAccessibilityButtonCallback () register callback.
Note: This feature only works on devices that provide software-rendered navigation areas. Always use isAccessibilityButtonAvailable (), and by implementing onAvailabilityChanged () according to the barrier-free function button available to respond to change. This way, users can always access your service functionality, even if the accessibility button is unsupported or becomes unavailable.
17. Independent volume adjustment
Android 8.0 introduced the STREAM_ACCESSIBILITY volume category, which allows you to individually control the volume of audio output from barrier-free services without affecting other sounds on your device.
To use this new flow type to control accessibility service volume, set the FLAG_ENABLE_ACCESSIBILITY_VOLUME option in accessibility Services. You can then change the accessibility service audio volume for your device using adjustStreamVolume().
18. Fingerprint gestures
Your accessibility service can also respond to an alternative input mechanism that slides along the device’s fingerprint sensor in a specific direction (up, down, left, and right). To receive callbacks about these interactions, complete the following series of steps:
- 1. The statement
USE_FINGERPRINT
Permissions andCAPABILITY_CAN_REQUEST_FINGERPRINT_GESTURES
Function. -
- in
Android: accessibilityFlags attribute set
FLAG_REQUEST_FINGERPRINT_GESTURES ‘flag.
- in
-
- use
registerFingerprintGestureCallback()
Register a callback. Keep in mind that not all devices include a fingerprint sensor. You can useisHardwareDetected()
Function identifies whether the device supports this sensor. Even for devices that include a fingerprint sensor, your service can only use the fingerprint sensor if it is not used for authentication purposes. To identify when this sensor is available, callisGestureDetectionAvailable()
Function and implementationonGestureDetectionAvailabilityChanged()
The callback.
- use
19. Word-level highlighting
To determine the position of the visible character in the TextView object, you can pass it as the first parameter in the EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY to refreshWithExtraData(). The Bundle object that you provided for refreshWithExtraData() as the second parameter is then updated to include a packable array of Rect objects. Each Rect object represents a bounding box for a particular character.
If your service uses a TextToSpeech object to read out what appears on the screen, you can get the exact time information about when the text-to-speech engine starts reading out individual composite words, provided that the text-to-speech engine provides this information. When the engine is about to start playing audio for a particular range of Text, the text-to-speech API notifies your service that the onRangeStart() function will be used to start reading the range of Text.
If you create your own TextToSpeechService implementation, you can use the rangeStart() function to support this new functionality.
20. Standardize single-ended range values
AccessibilityNodeInfo examples using AccessibilityNodeInfo. Some examples to show that RangeInfo interface elements can accept a range of values. When creating a range using rangeInfo.obtain () or retrieving the extreme values of this range using getMin() and getMax(), note that Android 8.0 specifies standardized single-ended ranges:
- For ranges with no minimum value, float.negative_infinity represents the minimum value.
- For ranges that do not have a maximum, float.positive_infinity indicates the maximum.
21. Prompt text
Android 8.0 contains several functions that can be used to interact with the prompt text of a text-editable object:
- The isShowingHintText() and setShowingHintText() functions display and set whether the current text content of a node represents the prompt text of the node, respectively. If the node does not contain editable text, it should not contain prompt text.
- To access the prompt text itself, use getHintText(). The system can call successfully even if an object does not currently display prompt text
GetHintText ().
Sequential gesture dispatch
Your service can now use GestureDescription. StrokeDescription last parameter in the constructor willContinue, specify the stroke order set belong to the same gesture
22. Security and privacy
permissions
Android 8.0 introduces several new telephone-related permissions:
ANSWER_PHONE_CALLS
Allows your application to answer incoming calls programmatically. To handle incoming calls in your application, you can useacceptRingingCall()
Function.READ_PHONE_NUMBERS
Permissions allow your application to read phone numbers stored on the device. These permissions are divided intodangerous
Category: belongs to the PHONE permission group.
#23. New account access and Discovery API
Android 8.0 introduces several improvements to the way applications access user accounts. For accounts managed by the authenticator, the authenticator can use its own policies when deciding whether to hide or show the account from the application. The Android system keeps track of applications that have access to specific accounts.
In previous versions of Android, apps that wanted to track a list of user accounts had to get updates for all accounts, including accounts with unrelated types. Android 8.0 added addOnAccountsUpdatedListener (Android. Accounts. OnAccountsUpdateListener, Android. OS. Handler, Boolean, Java.lang.string []) function that allows the application of a list of account types that specify that account changes should be received.
API changes AccountManager provides six new functions to help the authenticator manage which applications can view an account:
setAccountVisibility(android.accounts.Account, java.lang.String, int)
: Sets visibility levels for specific user accounts and package combinations.getAccountVisibility(android.accounts.Account, java.lang.String)
: Gets the visibility level of a specific user account and package combination.getAccountsAndVisibilityForPackage(java.lang.String, java.lang.String)
: allows the authenticator to get the visibility level of the account and the given package.getPackagesAndVisibilityForAccount(android.accounts.Account)
: allows the authenticator to get stored visibility values for a given account number.addAccountExplicitly(android.accounts.Account, java.lang.String, android.os.Bundle, java.util.Map<java.lang.String, java.lang.Integer>)
: allows the authenticator to initialize the visibility value of the account.addOnAccountsUpdatedListener(android.accounts.OnAccountsUpdateListener, android.os.Handler, boolean, java.lang.String[])
Will:OnAccountsUpdateListener
Listener added toAccountManager
Object. This listener is invoked whenever the list of accounts on the device changes. Android 8.0 introduces two special package name values to usesetAccountVisibility(android.accounts.Account, java.lang.String, int)
Function specifies the visibility level of an unset application.PACKAGE_NAME_KEY_LEGACY_VISIBLE
Visibility values are applied to haveGET_ACCOUNTS
Application with permissions, and the target Android version is lower than Android 8.0, or its signature matches an authenticator for any Android version.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE
Provides default visibility values for previously unset applications. For such applications,PACKAGE_NAME_KEY_LEGACY_VISIBLE
Do not apply.
For more information about the new account access and discovery API, see the AccountManager and OnAccountsUpdateListener references.
24. Google Safe Browsing API
The WebView class now adds a Safe Browsing API to make web Browsing more secure. For more information, see the Google Safe Browsing API.
25. The test
Instrument test
Android 8.0 provides the following additional support for instrumental testing of applications.
Run against non-default application processes
You can now specify to run instrument-specific tests against processes other than the default process for your application. This configuration is useful if your application contains multiple action components running in different processes.
To define non-default process instrumentation tests, navigate to your manifest file, and then navigate to the required < Instrumentation > element. Add the Android :targetProcess attribute and set its value to one of the following:
- The name of a specific process.
- A comma-separated list of process names.
- Wildcard (“*”), allowing instrumentation tests to be run against any started process that executes code in the software package specified in the Android :targetPackage attribute. When performing instrument tests, you can check which process is being tested by calling getProcessName().
Reporting results during tests Now, by calling addResults(), you can report results when an instrument test is executed, rather than after the test.
A simulated Intent for testing
To make it easier to create isolated, separate interface tests for your application’s action components, Android 8.0 introduced the onStartActivity() function. The specific intent to deal with your test class calls, you can in the Instrumentation. The ActivityMonitor custom subclasses of a class to replace this function.
When your test class call intent, this function returns a stub Instrumentation. ActivityResult object, rather than performing intent itself. By using this simulated intent logic in your tests, you can focus on how your own action components prepare and handle intents that you pass to different action components or completely different applications.
26. Runtime and tools
Platform optimization
Android 8.0 introduces runtime and other optimizations for the platform that will lead to several performance improvements. These optimizations include concurrent compression garbage collection, more efficient memory utilization, and code areas.
They can speed up startup times and lead to better performance for OS and applications.
Updated Java support
Android 8.0 adds support for more OpenJDK Java apis:
- In its eight
java.time
. - Its 7 of
java.nio.file
和java.lang.invoke
. For more details about the classes and functions in these newly added packages, refer to the API reference documentation.
If you want to use Java 8 language features in Android Studio, you should download the latest preview version.
The updated ICU4J Android Framework API Android 8.0 extends the ICU4J Android Framework API — a subset of the ICU4J API — for use by developers in the Android.icu package. These apis use localized data that is available on the device. As a result, you do not need to compile the ICU4J library in APK, thereby reducing the APK footprint.
For detailed updates to the supported ICU4J API, read the release notes. Android Enterprise edition has introduced new enterprise features and apis for devices running Android 8.0. Important functions include:
Work data in fully managed devices allows companies to manage work data and personal data separately. API delegates allow device owners and profile owners to assign application management to other applications. User experience improvements in the configuration process (including new customization options) shorten the setup time. New control options for Bluetooth, WLAN, backup, and security allow companies to manage devices more finely. Network operation component logging helps enterprises track down problems. For more information on these and other new Android Enterprise apis and features, see Android in the Enterprise.
At this point, this has ended, if there is wrong place, welcome your suggestion and correction. Meanwhile, I look forward to your attention. Thank you for reading. Thank you!
If there is infringement, please contact xiaobian, xiaobian is deeply sorry for this, xiaobian will delete the article, immediately stop infringement, please forgive me.
Since all see here, get two red envelopes in the walk! The following two red packets can be collected every day
1. Alipay search 522398497, or scan the Alipay red envelope poster.
2. Wechat red envelopes. You can get red envelopes by scanning wechat