HƯỚNG DẪN LẬP TRÌNH ANDROID CHO NGƯỜI MỚI BẮT ĐẦU

The phonghopamway.com.vn12 platkhung includes behavior changes that mayaffect your phầm mềm. The following behavior changes apply khổng lồ all apps when theyrun on phonghopamway.com.vn12, regardless of targetSdkVersion. You shouldthử nghiệm your phầm mềm and then modify it as needed to tư vấn these properly, whereapplicable.

Bạn đang xem: Hướng dẫn lập trình android cho người mới bắt đầu

Make sure khổng lồ also Review the menu of behavior changes that only affect appstargeting phonghopamway.com.vn12.

User experience

Stretch overscroll effect

On devices running phonghopamway.com.vn 12 & higher, the visual behavior for overscrollevents changes.

On phonghopamway.com.vn 11 và lower, an overscroll sự kiện causes the visual elements khổng lồ havea glow; on phonghopamway.com.vn 12 & higher, the visual elements stretch and bounce back ona drag sự kiện và they fling và bounce bachồng on a fling sự kiện.

For more information, see the guide to lớn animating scrollgestures.

App splash screens

If you have previously implemented a custom splash screen in phonghopamway.com.vn 11 orlower, you’ll need to migrate your app lớn the SplashScreen API lớn ensure thatit displays correctly starting in phonghopamway.com.vn 12. Not migrating your ứng dụng will resultin a degraded or unintended app launch experience.

For instructions, see Migrate your existing splash screenimplementation khổng lồ phonghopamway.com.vn 12.

Additionally, starting in phonghopamway.com.vn 12, the system always applies the new phonghopamway.com.vnsystem mặc định splash screen oncold andwarm starts for all apps.By mặc định, this system mặc định splash screen is constructed using your app’slauncher icon element và thewindowBackground of yourtheme (if it's a single color).

For more details, see the splash screens phonghopamway.com.vn guide.

Web intent resolution

Starting in phonghopamway.com.vn12 (API level31), a generic web intent resolves khổng lồ anactivity in your app only if your phầm mềm is approved for the specific domaincontained in that web intent. If your ứng dụng isn't approved for the domain name, theweb intent resolves to the user's mặc định browser phầm mềm instead.

Apps can get this approval by doing one of the following:

If your phầm mềm invokes website intents, consider adding a prompt or dialog that asksthe user lớn confirm the action.

Immersive sầu mode improvements for gesture navigation

phonghopamway.com.vn 12 consolidates existing behavior khổng lồ make it easier for users toperform gesture navigation commands while in immersivemode. Inaddition, phonghopamway.com.vn 12 provides backward compatibility behavior for stickyimmersivemode.

Display#getRealSize & getRealMetrics: deprecation và constraints

phonghopamway.com.vn devices are available in many different khung factors, such as largescreens, tablets, & foldables. To render content appropriately for eachdevice, your app needs lớn determine the screen or display kích cỡ. Over time,phonghopamway.com.vn has provided different APIs for retrieving this information. In phonghopamway.com.vn11, we introduced the WindowMetricsAPI và deprecated these methods:

In phonghopamway.com.vn 12 we're continuing to recommkết thúc using WindowMetrics, and aredeprecating these methods:

To mitigate the behavior of applications using Display APIs to retrieve sầu theapplication's bounds, phonghopamway.com.vn 12 constrains the values returned by the APIsfor apps that are not fully resizable. This could have an impact onapps that are using this information with MediaProjection.

Apps should use the WindowMetrics APIs lớn query the bounds oftheir window, and Configuration.densityDpito query the current mật độ trùng lặp từ khóa.

For broader compatibility with older versions of phonghopamway.com.vn, you can use theJetpaông chồng WindowManager library, whichincludes a WindowMetrics classthat supports phonghopamway.com.vn 4.0 (API level 14) and higher.

Examples of how to use WindowMetrics

First, be sure your app's activities are fully resizable.

An activity should rely upon WindowMetrics from an activity context for anyUI-related work, particularlyWindowManager.getCurrentWindowMetrics()or Jetpack'sWindowMetricsCalculator.computeCurrentWindowMetrics().

If your app creates a MediaProjection, the bounds must be correctly sizedsince the projection captures the display partition in which the projector appis running.

If the tiện ích is fully resizable, the activity context returns the correct boundslike so:


Kotlin

val projectionMetrics: WindowMetrics = activityContext .getSystemService(WindowManager::class.java).maximumWindowMetrics

Java

WindowMetrics projectionMetrics = activityContext .getSystemService(WindowManager.class).getMaximumWindowMetrics();
If the phầm mềm is not fully resizable, it must query from a WindowContextinstance & retrieve the WindowMetrics of the activity bounds usingWindowManager.getMaximumWindowMetrics()or the Jetpaông xã methodWindowMetricsCalculator.computeMaximumWindowMetrics().


Kotlin

val windowContext = context.createWindowContext(mContext.display!!, WindowManager.LayoutParams.TYPE_APPLICATION, null)val projectionMetrics = windowContext.getSystemService(WindowManager::class.java) .maximumWindowMetrics

Java

Context windowContext = context.createWindowContext(mContext.getDisplay(), WindowManager.LayoutParams.TYPE_APPLICATION, null);WindowMetrics projectionMetrics = windowContext.getSystemService(WindowManager.class) .getMaximumWindowMetrics();
Note: Any library that uses MediaProjection should also follow this advice andquery the appropriate WindowMetrics.

All apps in multi-window mode

phonghopamway.com.vn12 makes multi-window mode standard behavior.

On large screens (sw >= 600dp), the platkhung supports all apps in multi-windowmode regardless of ứng dụng configuration. IfresizeableActivity="false",the tiện ích is put into lớn compatibility mode when necessary to accommodate displaydimensions.

On small screens (sw minWidthandminHeightkhổng lồ determine whether the activity can run in multi-window mode. IfresizeableActivity="false",the phầm mềm is prevented from running in multi‑window mode regardless of minimumwidth and height.

For more information, see Multi-window support.

Camera preview on large screens

Camera apps generally assume a fixed relationship between the orientation ofthe device & the aspect ratio of the camera pĐánh Giá. But large screen formfactors, such as foldable devices, và display modes such as multi-window andmulti-display, challenge that assumption.

On phonghopamway.com.vn12, camera apps that request a specific screenorientation & are not resizable (resizeableActivity="false") automaticallyenter inset portrait mode, which ensures the proper orientation và aspectratio of the camera pĐánh Giá. On foldables and other devices that have sầu a camerahardware abstraction layer (HAL),additional rotation is applied khổng lồ the camera output to lớn compensate for camerasensor orientation, & the camera output is cropped lớn match the aspect ratioof the app's camera pnhận xét. The cropping và extra rotation ensure properpresentation of the camera preview regardless of device orientation và foldedor unfolded state of the device.

UX delay for foreground service notifications

To provide a streamlined experience for short-running foregroundservices, devices that runphonghopamway.com.vn12 or higher can delay the display of foreground servicenotifications by 10 seconds, with a fewexceptions. Thischange gives short-lived tasks a chance khổng lồ complete before their notificationsappear.

Performance

Restricted App Standby Bucket

phonghopamway.com.vn11 (API level30) introduced the restrictedbucket as an App StandbyBucket. Starting in phonghopamway.com.vn12, this bucket is active by mặc định.The restricted bucket has the lowest priority (and the highest restrictions) ofall the buckets. The buckets in order of priority from high lớn low are:

Active: App is currently being used or was very recently used.Working set: App is in regular use.Frequent: App is often used, but not every day.Rare: App is not frequently used.Restricted: App consumes a great deal of system resources, or may exhibitundesirable behavior.

The system considers your app's behavior, in addition to usage patterns, todecide whether khổng lồ place your phầm mềm in the restricted bucket.

Your phầm mềm is less likely to be placed in the restricted bucket if your tiện ích usessystem resources more responsibly. Also, the system places your phầm mềm in a lessrestrictive bucket if the user interacts directly with your app.

Chechồng whether your app is in the restricted bucket

To kiểm tra whether the system has placed your app in the restricted bucket, callgetAppStandbyBucket().If the return value of this method is STANDBY_BUCKET_RESTRICTED, then your appis in the restricted bucket.

Xem thêm: Công Ty Cổ Phần Máy Và Công Nghệ Thông Tin, Tuyển Dụng Mới Nhất Năm 2021

Test the restricted bucket behavior

To thử nghiệm how your ứng dụng behaves when the system places your app into lớn the restrictedbucket, you can manually move your tiện ích to lớn that bucket. To bởi vì so, run thefollowing commvà in a terminal window:

adb shell am set-standby-bucket PACKAGE_NAME restricted

Security và privacy

Approximate location


*
Figure 1. System permissions dialog that allows the user to lớn grant approximate location information.
On devices that run phonghopamway.com.vn12 or higher, users canrequest that your app haveaccess khổng lồ only approximate locationinformation.

Note: If your app requests ACCESS_COARSE_LOCATION but notACCESS_FINE_LOCATION, then this change doesn't affect your tiện ích.

If your phầm mềm requests theACCESS_FINE_LOCATIONruntime permission, you should also request theACCESS_COARSE_LOCATIONpermission lớn handle the case where the user grants approximate location accesskhổng lồ your phầm mềm. You should include both permissions in a single runtimerequest.

Caution: On some releases of phonghopamway.com.vn12, this change only affectsapps that target phonghopamway.com.vn12 or higher. In those releases, if yourapp requests ACCESS_FINE_LOCATION, it must also requestACCESS_COARSE_LOCATION to lớn show the system permissions dialog.

The system permissions dialog includes the following options for the user,as shown in figure 1:

Precise: Provides access to precise location information.Approximate: Provides access only lớn approximate location information.

Microphone và camera toggles

Supported devices that run phonghopamway.com.vn12 or higher allow users toenable và disable camera & microphone access for all apps on the device, bypressing a single toggle option. Users can access the toggleable options fromQuiông xã Settings, as shown infigure 1, or from the Privacy screen in system settings.

Learn more about thesetoggles, và how khổng lồ checkthat your tiện ích follows best practices regarding theCAMERA andRECORD_AUDIOpermissions.

Microphone & camera indicators

On devices that run phonghopamway.com.vn12 or higher, when an phầm mềm accessesthe microphone or camera, an icon appears in the status bar.

Learn more about theseindicators and how tokiểm tra that your app follows best practices regarding theCAMERA andRECORD_AUDIOpermissions.


*
Figure 2. Microphone và camera toggles in Quiông chồng Settings.
*
Figure 3. Microphone and camera indicators, which show recent data access.

Permission package visibility

On devices that run phonghopamway.com.vn12 or higher, apps that targetphonghopamway.com.vn11 (API level30) or higher and that Hotline one of following methodsreceive a filtered phối of results, based on the app's packagevisibility inkhổng lồ other apps:

BouncyCastle implementation removed

phonghopamway.com.vn12 removes manyBouncyCastle implementations ofcryptographic algorithms that were previously deprecated, including all AESalgorithms. The system instead uses theConscrypt implementations ofthese algorithms.

This change affects your tiện ích if any of the following are true:

Your tiện ích uses 512-bit key sizes. Conscrypt doesn't support this key size.If necessary, update your app's cryptography xúc tích và ngắn gọn to lớn use different key sizes.

Clipboard access notifications

On phonghopamway.com.vn12 & higher, when an phầm mềm callsgetPrimaryClip()to lớn access clip data from a differentapp for the first time, a toast messagenotifies the user of this clipboard access.

The text inside the toast message contains the following format:APP.. pasted from your clipboard.

Note: Your ứng dụng might callgetPrimaryClipDescription()to receive sầu information about the current data that's on theclipboard. When your phầm mềm calls thismethod, the system doesn't show a toast message.Information about text in clip description

On phonghopamway.com.vn12 & higher, getPrimaryClipDescription() candetect the following details:

Apps can"t cthua trận system dialogs

To improve sầu user control when interacting with apps và the system, theACTION_CLOSE_SYSTEM_DIALOGSintent action is deprecated as of phonghopamway.com.vn12. Except for a fewspecial cases, when your phầm mềm tries khổng lồ invokean intent that contains this action, thesystem does one of the following based on your app's target SDK version:

Exceptions

In the following cases, an tiện ích can still cthua thảm system dialogs onphonghopamway.com.vn12 or higher:

Untrusted touch events are blocked

To preserve system security và a good user experience,phonghopamway.com.vn12 prevents apps from consuming touchevents where an overlay obscures the ứng dụng in an unsafe way.In other words, the system blocks touches that pass through certain windows,with a few exceptions.

Affected apps

This change affects apps that choose to lớn let touches pass through their windows,for example by using theFLAG_NOT_TOUCHABLEflag. Several examples include, but aren't limited to, the following:

Activity windows that use the FLAG_NOT_TOUCHABLE flag.Exceptions

In the following cases, "pass-through" touches are allowed:

Interactions within your phầm mềm. Your phầm mềm shows the overlay, và the overlayappears only when the user is interacting with your tiện ích.

Trusted windows. These windows include (but aren't limited to) thefollowing:

Note: Windows of typeTYPE_APPLICATION_OVERLAYaren't trusted.

Sufficiently translucent system alert windows. The system considers a setof system alert windows to lớn be sufficiently translucent when the combined opacityis less than or equal khổng lồ the system's maximum obscuring opathành phố for touches.In phonghopamway.com.vn12, this maximum opađô thị is 0.8 by mặc định.

Detect when an untrusted touch is blocked

If a touch action is blocked by the system,Logcat logs the following message:

Untrusted touch due to lớn occlusion by PACKAGE_NAMETest the changeUntrusted touches are blocked by default on devices that runphonghopamway.com.vn12 or higher. To allow untrusted touches, runthe following ADB command in a terminal window:

# A specific appadb shell am compat disable BLOCK_UNTRUSTED_TOUCHES com.example.app# All apps# If you"d still lượt thích to see a Logcat message warning when a touch would be# blocked, use 1 instead of 0.adb shell settings put global block_untrusted_touches 0To revert the behavior to lớn the mặc định (untrusted touches are blocked), run thefollowing command:

# A specific appadb shell am compat remix BLOCK_UNTRUSTED_TOUCHES com.example.app# All appsadb shell settings put global block_untrusted_touches 2

Activity lifecycle

Root launcher activities are no longer finished on Bachồng press

phonghopamway.com.vn 12 changes the default handling of the system Baông chồng press on launcheractivities that are at the root of their tasks. In previous versions, the systemwould finish these activities on Baông chồng press. In phonghopamway.com.vn 12, the system now movesthe activity and its task khổng lồ the background instead of finishing the activity.The new behavior matches the current behavior when navigating out of an appusing the Home button or gesture.

Note: The system applies the new behavior only to launcher activities that arethe root of their tasks—that is, lớn activities that declare an Intentfilter with bothACTION_MAIN andCATEGORY_LAUNCHER. Forother activities, the system handles Back press as it did before, by finishingthe activity.

For most apps, this change means that users who use Baông chồng to lớn navigate out of yourphầm mềm are able to more quickly resume your phầm mềm from a warm state,instead of having khổng lồ completely restart the tiện ích from acold state.

We recommover testing your apps with this change. If your phầm mềm currently overridesonBackPressed() khổng lồ handleBaông xã navigation and finish the Activity, update your implementation lớn callthrough khổng lồ super.onBackPressed() instead of finishing. Callingsuper.onBackPressed() moves the activity và its task to lớn the background whenappropriate and provides a more consistent navigation experience for usersacross apps.

Also note that, in general, we recommkết thúc using the phonghopamway.com.vnX Activity APIs forproviding custom back navigation,rather than overriding onBackPressed(). The phonghopamway.com.vnX Activity APIsautomatically defer khổng lồ the appropriate system behavior if there are nocomponents intercepting the system Baông chồng press.

Graphics và images

Improved refresh rate switching

In phonghopamway.com.vn 12, refresh rate changes usingsetFrameRate()can happen regardless of whether the display supports a seamless transition tothe new refresh rate; a seamless transition is one that doesn't have sầu any visualinterruptions, such as a black screen for a second or two. Previously, if thedisplay did not tư vấn a seamless transition, it would typically continue usingthe same refresh rate after setFrameRate() is called. You can determine inadvance whether the transition khổng lồ the new refresh will likely be seamless bycalling getAlternativeRefreshRates().Generally, the callback onDisplayChanged()is called after the refresh rate switch completes, but for someexternally-connected displays, it is called during a non-seamless transition.