應用程式權限最佳做法

文章推薦指數: 80 %
投票人數:10人

如需查看有關Android 權限的一般資訊,請參閱權限總覽一文。

... 使用者可在系統提出要求時「以及」在設定中拒絕個別權限,但對於因此而導致功能異常 ... Platform AndroidStudio GooglePlay Jetpack Kotlin Docs Games Language English BahasaIndonesia Español–AméricaLatina Português–Brasil TiếngViệt 中文–简体 中文–繁體 日本語 한국어 Signin Documentation Overview Guides Reference Samples Design&Quality Platform AndroidStudio GooglePlay Jetpack Kotlin Docs Overview Guides Reference Samples Design&Quality Games AppBasics Introduction Buildyourfirstapp OverviewCreateanAndroidprojectRunyourappBuildasimpleuserinterfaceStartanotheractivity Appfundamentals Appresources OverviewHandleconfigurationchanges Localization LocalizeyourappTestyourappwithpseudolocalesUnicodeandinternationalizationsupportLanguageandlocaleresolutionComplexXMLresources Resourcetypes OverviewAnimationColorstatelistDrawableLayoutMenuStringStyleFontMoretypes Appmanifestfile Overview Devices Devicecompatibility OverviewScreencompatibilityoverviewSupportdifferentpixeldensitiesDeclarerestrictedscreensupport MultipleAPKsupport OverviewCreatemultipleAPKsfordifferentAPIlevelsCreatemultipleAPKsfordifferentscreensizesCreatemultipleAPKsfordifferentGLtexturesCreatemultipleAPKswithseveraldimensionsSupportdifferentlanguagesandculturesSupportdifferentplatformversionsFiltersonGooglePlay Tablets,largescreens,andfoldables GetstartedwithlargescreensMediaprojectionEnhancedletterboxing BuildresponsiveUIs SupportdifferentscreensizesNavigationforresponsiveUIsMigrateyourUItoresponsivelayoutsActivityembeddingMulti-windowsupportInputcompatibilityonlargescreens Buildforfoldables LearnaboutfoldablesMakeyourappfoldawareTestyourapponfoldables Wear GetstartedPrinciplesofWearOSdevelopmentUpgradetothelatestversionofWearOSWearOSversusmobiledevelopmentWearOSuserinterface Gettingstarted WearOSdeveloperpathwayCreateandrunawearableappDebugaWearOSappCaptureWearUIscreenshots Overlays OverviewStandaloneappsAuthenticationRequestpermissionsDetectlocationPlayingaudioonwearablesAppearinRecentsandAppResume BuildingUIwithCompose UseJetpackComposeonWearOSButtonsCardsChipsDialogsListsPageindicatorsPickersPositionindicatorProgressindicatorSlidersSteppersSwipetodismissTogglechipsTimetext BuildingUIwithViews BuildView-basedUIsonWearOSHandledifferentwatchshapesScreenoptionsCreatelistsNavigationExitfullscreenactivitiesonWearShowconfirmationsKeepyourappvisibleonWear Tilesandcomplications TilesoverviewWatchfacecomplicationsExposedatatocomplications Notifications NotificationsonWearOSBridgingoptionsfornotificationsOngoingActivities Handlingdata SendandsyncdataonWearOSNetworkaccessandsynconWearOSAccesstheWearableDataLayerTransferassetsSendandreceivemessagesHandledatalayereventsSyncdataitemswiththeDataLayerAPI Userinput PhysicalbuttonsRotaryinputCreateinputmethodeditorsinWearVoice Healthservices OverviewActivedataandexercisePassivedataupdatesUsesyntheticdataprovidersEnhanceappcompatibility Design DesignprinciplesGettingstartedInteractiontypesScreenshapesNotificationsComplicationsTilesTilesdesignsystemOverlaysOngoingactivitiesConfirmationoverlayDisconnectionindicatorsPermissionmessagesSelectioncontrolsLaunchandlatencyNavigationPermissionsSigninHardwarebuttonsColorTypographyIconsDownloadsWearMaterialTheming Creatingwatchfaces OverviewDesignwatchfacesBuildawatchfaceserviceDrawwatchfacesAddingcomplicationstoawatchfaceCreatinginteractivewatchfacesProvideconfigurationactivitiesAddresscommonissuesImproveperformacewithhardwareaccelerationOptimizeperformanceandbatterylife WatchFaceStudio WatchFaceStudioKeyboardshortcutsManageaWatchFaceStudioprojectCreateawatchfacewithWatchFaceStudioBuildcomplicationsinWatchFaceStudioTagexpressionsLanguagesettingsAlways-oninWatchFaceStudioGyroeffectsBuildanduploadfromWatchFaceStudioTestyourwatchfaceFAQWearappqualityPackageWearOSappsDistributetoWearOSCreateWearOSappsforChinaWearOSreleasenotes AndroidTV Overview BuildTVApps OverviewGetstartedwithTVappsAndroidXTVlibrariesHandleTVhardwareManageTVcontrollersBuildTVlayoutsOn-screenkeyboardCreateTVnavigationBestpracticesfordrivingengagementonGoogleTV BuildTVplaybackapps Overview UIguidance&LeanbackAPI CreateacatalogbrowserProvideacardviewBuildadetailsviewUsetransportcontrolsPlaybackcontrolsonTVAddaguidedstepIntroducefirst-timeuserstoyourappImplementamediasessionBackgroundplaybackinaNowPlayingcardAudiocapabilitiesMatchcontentframerate HelpusersfindcontentonTV Overview RecommendTVcontent OverviewChannelsonthehomescreenVideoprogramattributesAudioprogramattributesGameprogramattributes WatchNext AddprogramsAttributesGuidelinesforappdevelopersGuidelinesforTVprovidersPreviewvideosRecommendationsinAndroidNandearlierMakeTVappssearchableSearchwithinTVApps BuildTVgames OverviewUseStreamProtectforlatency-sensitivestreamingapps BuildTVinputservices OverviewDevelopaTVinputserviceWorkwithchanneldataManageTVuserinteractionSupporttime-shiftingSupportcontentrecordingTVAppschecklist TVAccessibility AccessibilitybestpracticesTalkBackevaluationexamplesAdoptsystemcaptionsettingsCustomviewaccessibilitysupportCustomviewaccessibilitysample Releases Android12forTV Android13forTV(Beta) OverviewWhat'snewforTV AndroidforCars Overview Buildmediaappsforcars BuildmediaappsforcarsAddsupportforAndroidAutoAddsupportforAndroidAutomotiveOSBuildmessagingappsforAndroidAuto Buildnavigationandpointofinterestappsforcars UsingtheAndroidforCarsAppLibraryBuildpointofinterestappsforcarsBuildnavigationappsforcarsAddsupportforAndroidAutoAddsupportforAndroidAutomotiveOSBuildvideoappsforAndroidAutomotiveOSTestAndroidappsforcarsDistributeAndroidappsforcarsGooglePlayservicesforcarsNotificationsonAndroidAutomotiveOS ChromeOSdevices OverviewBuildingappsforChromeOSOptimizingAppsforChromeOSPreparingyourdevelopmentenvironmentAppManifestCompatibilityforChromebooksChromeOSDeviceSupportforAppsAppRenderingDifferencesonChromebooksWindowmanagementAdaptingGamesonChromeOSSmoothanimationonChromeOSTestCasesforAndroidAppsonChromeOS Apparchitecture Introduction Guidetoapparchitecture Overview UIlayer OverviewUIeventsDomainlayerDatalayerLearningpathway ArchitectureComponents UIlayerlibraries Viewbinding OverviewMigratefromKotlinsyntheticstoviewbinding Databindinglibrary OverviewGetstartedLayoutsandbindingexpressionsWorkwithobservabledataobjectsGeneratedbindingclassesBindingadaptersBindlayoutviewstoArchitectureComponentsTwo-waydatabinding Lifecycle-awarecomponents HandlelifecyclesViewModelLiveDataSaveUIstatesSavedStatemoduleforViewModelUseKotlincoroutineswithlifecycle-awarecomponents PagingLibrary OverviewLoadanddisplaypageddataPagefromnetworkanddatabaseTransformdatastreamsManageandpresentloadingstatesTestyourPagingimplementationMigratetoPaging3 Paging2 OverviewDisplaypagedlistsLoadpageddata Datalayerlibraries DataStore WorkManager OverviewGettingStarted How-ToGuides DefiningyourWorkRequestsWorkstatesManagingworkObservingintermediateWorkerprogressChainingworktogetherTestingWorkerimplementationIntegrationtestswithWorkManagerDebuggingWorkManager AdvancedConcepts ConfigurationandInitialization ThreadinginWorkManager OverviewThreadinginWorkerThreadinginCoroutineWorkerThreadinginRxWorkerThreadinginListenableWorkerSupportforlong-runningworkersMigratingfromFirebaseJobDispatcherMigratingfromGCMNetworkManager Appentrypoints Activities IntroductiontoactivitiesTheactivitylifecycleActivitystatechangesTestyouractivitiesTasksandbackstackProcessesandapplifecycleParcelablesandbundlesLoadersRecentsscreenRestrictionsonstartingactivitiesfromthebackground Appshortcuts OverviewCreateshortcutsAddcapabilitiesManageshortcutsBestpracticesforshortcuts Appnavigation PrinciplesofnavigationDesignfordifferentformfactorsHandleconfigurationchanges Navigationcomponent OverviewGettingstartedCreatedestinationsDesignnavigationgraphsNestedgraphsGlobalactionsNavigatetoadestinationSupportmultiplebackstacksConditionalnavigationPassdatabetweendestinationsCreateadeeplinkforadestinationAnimatetransitionsbetweendestinationsUpdateUIcomponentswithNavigationUIKotlinDSLInteractprogrammaticallyNavigatewithfeaturemodulesBestpracticesformulti-moduleprojectsTestnavigationAddnewdestinationtypesMigratetotheNavigationcomponent Fragments OverviewCreateafragmentFragmentmanagerFragmenttransactionsAnimatetransitionsbetweenfragmentsFragmentlifecycleSavingstatewithfragmentsCommunicatewithfragmentsWorkingwiththeappbarDisplayingdialogswithDialogFragmentDebugyourfragmentsTestyourfragments Applinks OverviewEnablinglinkstoappcontentVerifyapplinksCreateapplinksforinstantappsCreateswipeviewswithtabsusingViewPagerCreateswipeviewswithtabsusingViewPager2Providecustombacknavigation Dependencyinjection OverviewManualdependencyinjectionDependencyinjectionwithHiltHiltinmulti-moduleappsUseHiltwithotherJetpacklibrariesHilttestingguideHiltandDaggerannotationscheatsheet Dagger DaggerbasicsUsingDaggerinAndroidappsUsingDaggerinmulti-moduleapps AppStartup Coretopics Appcompatibility OverviewCompatibilityframeworktoolsRestrictionsonnon-SDKinterfaces Interactwithotherapps OverviewSendingtheusertoanotherappGettingaresultfromanactivityAllowingotherappstostartyouractivity Packagevisibility OverviewKnowwhichpackagesarevisibleautomaticallyDeclarepackagevisibilityneedsFulfillcommonusecasesTestpackagevisibility Intentsandintentfilters OverviewCommonintents Userinterface Overview Layouts OverviewBuildaresponsiveUIwithConstraintLayout AddmotiontoyourlayoutwithMotionLayout OverviewCarouselwithMotionLayoutMotionLayoutexamples MotionLayoutXMLreference OverviewCreatealistwithRecyclerViewAdvancedRecyclerViewcustomizationCreateacard-basedlayoutCreateatwopanelayout Improvinglayoutperformance OverviewOptimizinglayouthierarchiesRe-usinglayoutswithDelayedloadingofviewsLinearlayoutAdapterviewRelativelayout Customviewcomponents OverviewCreatingacustomviewclassImplementingcustomdrawingMakingtheviewinteractiveOptimizingtheviewDesigningforfoldables Lookandfeel MaterialdesignStylesandthemesDarkthemeRoundedcornersAdaptiveiconsAddafloatingactionbuttonCreateshadowsandclipviews Text AutosizingTextViewsDownloadablefontsFontsinXML Emoji SupportmodernemojiEmojicompatibilityMagnifierwidgetSpansButtonsCheckboxesRadiobuttonsTogglebuttonsSpinnersPickersTooltips Notifications OverviewCreateanotificationCreateanexpandablenotificationDisplaytime-sensitivenotificationsStartanactivityfromanotificationCreateagroupofnotificationsCreateandmanagenotificationchannelsModifyanotificationBadgeCreateacustomnotification Splashscreens OverviewMigrateyourexistingsplashscreenConversationsBubbles Addtheappbar OverviewSetuptheappbarAddandhandleactionsAddanupactionUseactionviewsandactionproviders Windowinsets OverviewDisplayedge-to-edgeImmersivemodeSupportdisplaycutoutsControlthesoftwarekeyboard Supportingswipe-to-refresh OverviewAddingswipe-to-refreshtoyourappRespondingtoarefreshgestureToastsoverview Pop-upmessagesoverview OverviewBuildanddisplayapop-upmessageAddanactiontoamessageDialogsMenus Settings OverviewOrganizeyoursettingsCustomizeyoursettingsUsesavedvaluesBuildahierarchyincodeHandleotherformfactorsPreferencecomponentsandattributes Search OverviewCreatingasearchinterfaceAddingrecentquerysuggestionsAddingcustomsuggestionsSearchableconfiguration Addingsearchfunctionality OverviewSettingupthesearchinterfaceStoringandsearchingfordataRemainingbackwardcompatibleReceiverichcontentCopyandpasteDraganddropPicture-in-picturesupport Creatingbackward-compatibleUIs OverviewAbstractingthenewAPIsProxyingtothenewAPIsCreatinganimplementationwitholderAPIsUsingtheversion-awarecomponentDevicecontrol Homechannelsformobileapps OverviewMediaHomeBooksMediaHomeVideoMediaHomeAudio Appwidgets OverviewCreateasimplewidgetEnhanceyourwidgetCreateanadvancedwidgetUsewidgetcollectionsProvideflexiblewidgetlayoutsEnablewidgetconfigurationBuildanappwidgethost Animations&transitions OverviewIntroductiontoanimationsPropertyanimationoverviewAnimatedrawablegraphicsRevealorhideaviewusinganimationMoveaviewusinganimationMoveaviewusingaflinganimationEnlargeaviewusingazoomanimationAnimatemovementusingspringphysicsAutoanimatelayoutupdatesAnimatelayoutchangesusingatransitionCreateacustomtransitionanimationStartanactivityusingananimationSlidebetweenfragmentsusingViewPagerSlidebetweenfragmentsusingViewPager2MigratefromViewPagertoViewPager2Additionalresources Images&graphics OverviewDrawablesoverviewVectordrawablesoverviewHandlingbitmapsSelectingcolorswiththepaletteAPIReducingimagedownloadsizesHardwareacceleration DrawingwithAGSLshaders OverviewDifferencesbetweenAGSLandGLSLUsingAGSLinyourAndroidappAGSLQuickReferenceOpenGLES DisplayinggraphicswithOpenGLES OverviewBuildinganOpenGLESenvironmentDefiningshapesDrawingshapesApplyingprojectionandcameraviewsAddingmotionRespondingtotouchevents Rendering OverviewReducingoverdrawPerformanceandviewhierarchiesAnalyzingwithprofileGPUrenderingEnhancinggraphicswithwidecolorcontent Audio&video Audio&videooverview Media3 Overview Gettingstarted UseamediasessiontomanageplaybackPlaymediainthebackground ExoPlayer ExoPlayerandMedia3ExoPlayertoMedia3mappingsMediacontrolsSupportedmediaformatsMediacodecs Mediaapparchitecture MediaapparchitectureoverviewUsingamediasession Buildinganaudioapp AudioappoverviewBuildingamediabrowserserviceBuildingamediabrowserclientMediasessioncallbacksUsingthemediacontrollertestapp Buildingavideoapp VideoappoverviewBuildingavideoplayeractivityMediasessioncallbacksCompatiblemediatranscodingRespondingtomediabuttonsHandlingchangesinaudiooutputManageaudiofocus TheGoogleAssistant TheGoogleAssistantandmediaappsMediaappsonGoogleAssistantdrivingmode Routingbetweendevices RoutingoverviewMediaRouteroverviewMediaRouteProvideroverviewControlamplitudewithVolumeShaperMediaPlayeroverviewMediaRecorderoverviewExoPlayerSharingaudioinputCapturevideoandaudioplaybackFramerateBestpracticesforsharingvideoAdditionalResourcesforMedia Services OverviewForegroundservicesBoundservicesAIDLoverview Backgroundtasks OverviewBackgroundthreadsBackgroundoptimizations Broadcasts OverviewImplicitBroadcastExceptions Managedeviceawakestate OverviewKeepthedeviceawakeSchedulealarmsUsingaListenableFuture Permissions OverviewEvaluatewhetheryourappneedspermissionsDeclareapppermissionsRequestapppermissionsExplainaccesstomoresensitiveinformationApppermissionsbestpracticesPermissionsusedonlyindefaulthandlersRestrictinteractionswithotherappsDefinecustompermissions Appdata&files OverviewStorageoverviewSavetoapp-specificstorage Savetosharedstorage OverviewMediaDocumentsandotherfilesDatasetsManageallfilesonastoragedeviceSavekey-valuedata Savedatainalocaldatabase OverviewDefinedatausingentitiesAccessdatausingDAOsDefinerelationshipsbetweenobjectsWriteasynchronousDAOqueriesCreateviewsintoadatabasePrepopulateyourdatabaseMigrateyourdatabaseTestanddebugyourdatabaseReferencecomplexdataMigratefromSQLitetoRoomSavedatausingSQLiteStorageusecasesandbestpractices Sharingsimpledata OverviewSendingsimpledatatootherappsReceivingsimpledatafromotherapps Sharingfiles OverviewSettingupfilesharingSharingafileRequestingasharedfileRetrievingfileinformation SharingfileswithNFC OverviewSendingfilestoanotherdeviceReceivingfilesfromanotherdevice Printingfiles OverviewPrintingphotosPrintingHTMLdocumentsPrintingcustomdocuments Contentproviders OverviewContentproviderbasicsCreatingacontentproviderOpenfilesusingstorageaccessframeworkCreateacustomdocumentproviderAppinstalllocation Userdata&identity OverviewAddsign-inworkflowShowabiometricauthenticationdialog Autofillframework OverviewOptimizeyourappforautofillBuildautofillservicesIntegrateautofillwithkeyboardsIdentifydeveloper-ownedappsReviewhowyourappcollectsandsharesuserdataAuditdataaccessGetauser-resettableadvertisingIDCalendarprovideroverview Contactsprovider OverviewRetrievingalistofcontactsRetrievingdetailsforacontactModifyingcontactsusingintentsDisplayingthequickcontactbadgeAccounttransfer Databackup OverviewBackupuserdataBackupkey-valuepairsTestbackupandrestoreBestpracticesforuniqueidentifiers Rememberandauthenticateusers OverviewRememberyouruserAuthenticatetoOAuth2servicesCreateacustomaccounttype Userlocation OverviewRequestlocationpermissionsGetthelastknownlocationChangelocationsettingsRequestlocationupdatesAccesslocationinthebackgroundCreateandmonitorgeofencesDetectwhenusersstartanactivityOptimizelocationforbatteryTestlocationworkflowsMigratetolocationandcontextAPIsAddmaps Touch&input OverviewInputevents Usingtouchgestures OverviewDetectcommongesturesTracktouchandpointermovementsAnimateascrollgestureSupportnavigationgesturesHandlemulti-touchgesturesDragandscaleManagetoucheventsinaViewGroup Handlingkeyboardinput OverviewSpecifyingtheinputmethodtypeHandlinginputmethodvisibilitySupportingkeyboardnavigationHandlingkeyboardactions Supportinggamecontrollers OverviewHandlingcontrolleractionsSupportingcontrollersacrossAndroidversionsSupportingmultiplegamecontrollers Inputmethodeditors CreatinganinputmethodImagekeyboardSpellingchecker Camera Chooseacameralibrary CameraX OverviewArchitectureConfiguration Usecases PreviewImagecaptureImageanalysisVideocapture Advancedtopics ExtensionsAPITransformoutputRotationsDevices Camera2 OverviewCameracapturesessionsandrequestsCameralensesandcapabilitiesUsemultiplecamerastreamssimultaneouslyCamerapreviewMulti-CameraAPIExtensionsAPI Camera(deprecated) OverviewTakephotosRecordvideosControlthecameraCameraAPI Sensors OverviewSensorsoverviewMotionsensorsPositionsensorsEnvironmentsensorsRawGNSSmeasurements Connectivity Overview Performingnetworkoperations OverviewConnecttothenetworkManagenetworkusageReadingnetworkstateOptimizenetworkaccessOptimizenetworkdatausageMonitorconnectivitystatusandconnectionmeteringParseXMLdata PerformnetworkoperationsusingCronet OverviewSendasimplerequestCronetrequestlifecycleUseCronetwithotherlibraries Reference org.chromium.net OverviewCallbackException CronetEngine Overview CronetEngine.Builder OverviewLibraryLoaderCronetExceptionInlineExecutionProhibitedExceptionNetworkExceptionQuicExceptionUploadDataProviderUploadDataProvidersUploadDataSink UrlRequest OverviewBuilderCallbackStatusStatusListener UrlResponseInfo OverviewHeaderBlockEnhanceyourappswith5GBuildclient-serverapplicationswithgRPC Transferringdatawithoutdrainingthebattery OverviewOptimizedownloadsforefficientnetworkaccessMinimizetheeffectofregularupdatesAvoidunoptimizeddownloads Reducenetworkbatterydrain OverviewCollectingnetworktrafficdataAnalyzingdatatrafficOptimizenetworkaccessOptimizeuser-initiatednetworkuseOptimizeapp-initiatednetworkuseOptimizeserver-initiatednetworkuseOptimizinggeneralnetworkuse TransferdatausingSyncAdapters OverviewCreateaStubAuthenticatorCreateaStubContentProviderCreateaSyncAdapterRunaSyncAdapter Bluetooth OverviewSetupBluetoothFindBluetoothdevicesConnectBluetoothdevicesTransferBluetoothdataBluetoothpermissionsBluetoothprofilesCompaniondevicepairing BluetoothLowEnergy OverviewFindBLEdevicesConnecttoaGATTserverTransferBLEdata NFC OverviewNFCbasicsAdvancedNFCHost-basedcardemulationoverview Telecom OverviewBuildacallingappPreventcallerIDspoofingTelephonyIDs Wi-Fi Wi-FiscanningoverviewWi-Fipeer-to-peerWi-FiAwareoverviewWi-FilocationwithRTTLocalOnlyHotspot Discoverandconnect OverviewUsenetworkservicediscoveryCreateP2PconnectionswithWi-FiUseWi-FiP2PforservicediscoveryWi-FiEasyConnect Wi-Fiinfrastructure Wi-FiinfrastructureoverviewWi-FisuggestionAPIforinternetconnectivityWi-FiNetworkRequestAPIforpeer-to-peerconnectivityPasspointSavenetworksandPasspointconfigurations USB OverviewAccessoryoverviewHostoverviewUWBVPNSessioninitiationprotocoloverviewOpenMobileAPIreadersupport Renderscript OverviewAdvancedRenderScriptMigratefromRenderScript RuntimeAPIreference OverviewNumericaltypesObjecttypesConversionfunctionsMathematicalconstantsandfunctionsVectormathfunctionsMatrixfunctionsQuaternionfunctionsAtomicupdatefunctionsTimefunctionsandtypesAllocationdataaccessfunctionsObjectcharacteristicsfunctionsKernelinvocationfunctionsandtypesInput/outputfunctionsDebuggingfunctionsGraphicsfunctionsandtypesIndex Web-basedcontent OverviewBuildingwebappsinWebViewManagingWebViewobjectsLoadlocalcontentDarkenwebcontentUserprivacyinWebViewcrashreportingSupportingdifferentscreensinwebappsDebuggingwebappsBestpracticesforwebappsTestingagainstfutureversionsofWebView AndroidAppBundles OverviewConfigurethebasemoduleBuildandtestyourappbundleAddcodetransparencyTheappbundleformatFrequentlyaskedquestions GooglePlay GooglePlayBillingGooglePlayCorelibraries PlayPoints OverviewCreateproductsandpromotionsDetectanddeliverproductsTestproducts PlayAssetDelivery OverviewIntegrateassetdelivery(Kotlin&Java)Integrateassetdelivery(native)Integrateassetdelivery(Unity)TargettexturecompressionformatsTestassetdelivery PlayFeatureDelivery OverviewConfigureinstall-timedeliveryConfigureconditionaldeliveryConfigureon-demanddeliveryOn-demanddeliverybestpracticesConfigureinstantdeliveryAdditionalresources In-appreviews OverviewIntegrateusingKotlinorJavaIntegrateusingnativecodeIntegrateusingUnityTestin-appreviews In-appupdates OverviewSupportin-appupdates(KotlinorJava)Supportin-appupdates(Native)Supportin-appupdates(Unity)Testin-appupdates GooglePlayInstant OverviewofGooglePlayInstant Getstartedwithinstantapps Createaninstant-enabledappbundleUXbestpracticesforapps Getstartedwithinstantgames OverviewUnitypluginUXbestpracticesforgamesMigratetoAndroidAppBundlesImplementclouddeliveryofassetsSupportGooglePlayGamesServicesInstantPlaygamesInstantPlaygameschecklistReducethesizeofyourinstantapporgameAddadstoyourinstantapporgameProvidemultipleentrypoints IntegratewithFirebase AddGoogleAnalyticsforFirebasetoyourinstantappUseFirebaseDynamicLinkswithinstantappsTechnicalrequirementschecklistGooglePlayInstantpolicy Resources ReferenceCodesamplesSDKreleasenotesInstantAppIntents Support KnownissuesStackOverflowPlayDeveloperAPI PlayInstallReferrer Overview PlayInstallReferrerLibrary OverviewReferenceReleasenotesPlayInstallReferrerAPIPlayIntegrityAPI PlayRequirements PlayPoliciesTargetAPILevelSupport64-bitarchitectures ApplicationLicensing OverviewLicensingOverviewSettingUpforLicensingAddingServer-SideVerificationAddingClient-SideVerificationLicensingReferenceAPKExpansionFiles GoogleAssistant Overview Build AppActionsoverviewImplementbuilt-inintentsCreateshortcuts.xmlPushdynamicshortcutstoAssistantReleasenotes Test GoogleAssistantplugin Grow OverviewIn-AppShortcutPromoSDK Addmorefeatures CustomintentsAndroidwidgetsForegroundappinvocationInlineinventoryWebinventoryAssistantsharingReadIt Actions.xml Actions.xmlmigrationguideActions.xmloverviewBuildAppActionsCreateactions.xmlWebinventoryAppActionstesttoolAndroidSlicesTroubleshootingSupport Slices OverviewGettingStartedSlicetemplates On-devicesearch Games Develop Overview AndroidGameDevelopmentKit(AGDK) OverviewLibrariesDownloadReleasenotesAndroidStudio AndroidGameDevelopmentExtensionforVisualStudio OverviewQuickstartConfigureaprojectDebuggerMeasureappperformanceModifybuild.gradlefilesforAndroidStudioSamplesReleasenotes AndroidGPUInspector OverviewQuickstartSupporteddevices Systemprofiling OverviewViewasystemprofileGPUperformancecounters Analyzeasystemprofile FrameprocessingtimesMemoryefficiencyTexturememorybandwidthusageVertexmemorybandwidthusageThreadscheduling Frameprofiling Overview Analyzeaframeprofile MostexpensiverenderpassesVertexformatsShaderperformance FrameProfilerUI PerformancepaneCommandspaneFramebufferpaneGeometrypaneReportpaneShaderpaneMemorypaneStatepaneTexturespaneTexturepanePipelineviewpaneSupportedVulkanextensionsTroubleshootAndroidPerformanceTuner MemoryAdviceAPI OverviewGetstarted Improve ImprovegameperformanceReducegamesize Improvedeviceavailability Support64-bitarchitecturesSupportallscreens GameMode OverviewOptimizewithGameModeAPIGameModeinterventions VulkanandOpenGL 3DassetoptimizationVulkanPrerotationVertexdatamanagement Distribute Overview GooglePlayGamesServices OverviewGetstartedDownloads SetupPlayConsole SetupPlayGamesServicesEnablefeaturesCloudprojectmanagementPublish Managefeatures AchievementsLeaderboardsEventsSavedgamesFriendsSign-in UsetheAPIs Android GetstartedSign-inEnableserver-sideaccessAnti-piracy Addfeatures AchievementsLeaderboardsFriendsSavedgamesEventsPlayerstatsTroubleshooting Unity OverviewGetstarted Addfeatures AchievementsLeaderboardsSavedgamesEventsFriendsPlayerstatsCAPI-comingsoon PublishingAPI OverviewGetstartedUploadimagesManagementAPI Requirementsandguidelines QualitychecklistBrandingguidelinesQuotaandratelimitsDatadisclosurerequirementsTermsofserviceSupport GooglePlayGamesforPC OverviewGetstarted Setupyourgame PCcompatibilityGraphicsconfiguration Deviceinput Setupinput InputSDK OverviewQuickstart Continuity OverviewContinuityrequirementsVerifyingrequirementsExistingidentitysolutionsUsetheemulatorTestonChromeOS Publishanddeploy PackageSubmitUpdateFAQGooglePlayInstantPlayasyoudownload Health&fitnessapps HealthConnect Introduction Platformoverview ArchitectureDeveloperfunctionalityGetstarted Dataanddatatypes IntroductionDatatypesDifferentialchangesAPI Commonworkflows WritedataReaddataDeletedataAggregatedataWorkwithsessionsExceptionsFrequentlyaskedquestions HealthConnectguidelines HealthConnectpolicyrequirementFAQsUXdeveloperguidance Migrate HealthConnectAPIcomparisonguideFitAndroidAPItoHealthConnectmigrationguide Bestpractices Testing TestappsonAndroid Fundamentals FundamentalsoftestingAndroidappsWhattotestinAndroidUsingtestdoublesinAndroid Localtests Buildlocaltests Instrumentedtests BuildinstrumentedtestsAutomateUItests AndroidXtestlibraries SetupprojectforAndroidXTestJUnit4ruleswithAndroidXTestAndroidJUnitRunner Espresso EspressoEspressobasicsEspressosetupinstructionsEspressocheatsheetEspressoidlingresourcesEspresso-IntentsEspressolistsMultiprocessEspressoEspressorecipesEspressoWebAccessibilitycheckingAdditionalResourcesforEspresso Testingothercomponents TestcontentprovidersTestyourserviceWriteautomatedtestswithUIAutomator Performance Overview Inspectingperformance OverviewAndroidStudioProfilers Profilingandtracing Systemtracing Overview Capturetrace CaptureatraceinAndroidStudioCaptureatraceonadeviceCaptureatracefromthecommandlineNavigateareport Customevents DefinecustomeventsCustomtraceeventsinnativecodeInspectGPUrendering Benchmarking Overview Macrobenchmark WritingabenchmarkCapturethemetricsControlyourappAddinginstrumentationarguments Microbenchmark OverviewWritingabenchmarkProfilingabenchmarkAddinginstrumentationargumentsBuildingwithoutGradleBenchmarkinginCI Measureperformance OverviewExamples Improvingperformance OverviewBaselineProfilesAppstartuplibrary Guides WorkinginthebackgroundPerformanceclassAppStandbyBucketsAppHibernationVerifyingAppBehaviorontheAndroidRuntime(ART) Solvingcommonproblems AppStartup Slowrendering KeepingyourappresponsiveImprovinglayoutperformanceRendering Memory OverviewofmemorymanagementMemoryallocationamongpropertiesManageyourapp'smemoryProcessesandthreads Batteryandpower OptimizefordozeandappstandbyMonitorthebatterylevelandchargingstateMonitorconnectivitystatusandconnectionmeteringDetermingandmonitordockingstateandtypeProfilebatteryusagewithBatterystatsandBatteryHistorianAnalyzepowerusewithBatteryHistorianTestpower-relatedissuesBackgroundoptimizationsReduceappsize Monitoringperformance Overview AndroidVitals OverviewStuckPartialWakeLocksExcessiveWakeupsExcessiveBackgroundWi-FiScansExcessiveBackgroundNetworkUsageANRsCrashesSlowRenderingFrozenFramesPermissionDenialsAppStartupTimeJankStatslibrary Accessibility Overview Buildandtestappsforaccessibility MakeappsmoreaccessiblePrinciplesforimprovingappaccessibilityTestyourapp'saccessibility Advancedtopics MakecustomviewsmoreaccessibleCreateyourownaccessibilityserviceAdditionalresources Privacy Privacybestpractices Security AppsecuritybestpracticesSecuritytipsSecuritywithdataSecuritywithdataacrossadditionalAndroidversionsSecuritywithHTTPSandSSLNetworksecurityconfigurationUpdatingyoursecurityprovidertoprotectagainstSSLexploits ProtectingagainstsecuritythreatswithSafetyNet OverviewSafetyNetAttestationAPIDiscontinuingSafetyNetAttestationPlayIntegrityAPISafetyNetSafeBrowsingAPISafetyNetreCAPTCHAAPISafetyNetVerifyAppsAPICryptographyAndroidKeystoreSystemVerifyinghardware-backedkeypairswithkeyattestationAndroidProtectedConfirmationSupportingDirectBootRunningembeddedDEXcodeAppsecurityimprovementprogram SDKs SDKbestpractices BuildforBillions OverviewConnectivityDevicecapabilityDatacostBatteryconsumptionUIandcontent BuildforEnterprise OverviewDeveloperguideWorkprofilesSetupmanagedconfigurations Appfeedback SendappfeedbacktoEMMsTestappfeedbackWorkcontactsDevicemanagementpolicies Devicemanagement OverviewBuildadevicepolicycontroller Dedicateddevices OverviewLocktaskmodeMultipleusersCookbookDevicecontrolNetworkingandtelephonySecuritySystemupdatesNetworkactivitylogging Androidversions OverviewAndroid12Android11Android10Android9Android8.0Android7.0Deviceadministration AndroidDevelopers Docs Guides 應用程式權限最佳做法 權限要求可保護裝置提供的機密資訊,因此只有在應用程式必須存取這類資訊來維持運作時才能使用。

本文件提示了幾種方法,讓您不需要求這類資訊,就能夠執行相同(或更優質的)功能;此處並未完整探討Android作業系統中的權限運作方式。

如需查看有關Android權限的一般資訊,請參閱權限總覽一文。

如要進一步瞭解如何透過程式碼與權限搭配運作,請參閱要求應用程式權限一文。

Android6.0以上版本的權限 在Android6.0(API級別23)以上版本中,應用程式可以在執行階段(而非在安裝前)向使用者要求權限。

這樣一來,應用程式就能在確實需要相關服務或由該服務保護的資料時要求權限。

儘管這項做法不一定會改變應用程式的整體行為,不過確實會造成一些與使用者機密資料處理方式相關的變動: 增加情境式的內容 當使用者要存取相關權限群組涵蓋的功能時,請在執行階段中依據應用程式的使用情境提示使用者授予權限。

使用者對於要求取得權限時的使用情境更為敏感,因此如果您要求的權限與應用程式的用途不符,就更應該向使用者詳細說明您要求權限的原因。

在要求權限時,以及在使用者拒絕要求後顯示的對話方塊中,請盡可能提供相關說明。

如要提高使用者接受權限要求的可能性,建議您只在需要執行特定功能時才提出要求。

舉例來說,只有當使用者點選麥克風按鈕時,才提示要求麥克風存取權。

使用者在預期行使特定權限時,更有可能允許授予權限。

注意:請勿在應用程式啟動時要求所有權限,避免讓使用者負擔過重。

請對使用者展現禮貌風度,並且只在他們需要存取特定功能時才要求權限。

權限授予更具彈性 使用者可在系統提出要求時「以及」在設定中拒絕個別權限,但對於因此而導致功能異常中斷的情況,仍可能感到不知所措。

建議您監控拒絕授予權限的使用者人數(例如使用GoogleAnalytics(分析)),以便據此重構出不依賴該權限的應用程式,或是提供更詳盡的說明,讓使用者瞭解為何必須授予權限才能讓應用程式順利運作。

此外,當使用者拒絕權限要求或在設定中關閉權限時,您必須確保應用程式能夠處理例外狀況。

增加事務性負擔 系統會要求使用者逐一授予多個權限群組的權限,而不是一次授予所有權限群組的權限。

這樣一來,盡量減少要求的權限數量就變得極為重要。

這麼做會增加使用者的授權負擔,進而提高至少有一項要求遭拒的可能性。

需要成為預設處理常式的權限 部分應用程式需要存取通話記錄和簡訊相關的使用者機密資訊。

如果想要求通話記錄和簡訊的特定權限,並將應用程式發布至Play商店,您必須先提示使用者將應用程式設為特定核心系統函式的「預設處理常式」,才能要求這些執行階段權限。

如要進一步瞭解預設處理常式,包括說明如何向使用者顯示預設處理常式提示的規範,請參閱僅供預設處理常式使用的權限指南。

瞭解搭配運作的資料庫 您在應用程式中使用的資料庫有時會需要權限。

舉例來說,廣告和數據分析資料庫可能需要LOCATION權限群組的存取權,才能執行所需功能。

但從使用者的觀點來看,權限要求是來自您的應用程式,而非資料庫。

如同使用者會選擇針對相同功能使用較少權限的應用程式,開發人員也應檢查自己的程式庫,並選擇不會使用非必要權限的第三方SDK。

舉例來說,假設您使用的程式庫提供位置資訊功能,請確認您並未要求FINE_LOCATION權限(除非您要使用指定地區功能)。

限制位置資訊的背景存取權 應用程式在背景執行時,位置資訊的存取權必須攸關應用程式的核心功能,且能明確展現對使用者的好處。

測試兩種權限模型 在Android6.0(API級別23)以上版本中,使用者會在執行階段授予及撤銷應用程式權限,而不是在安裝應用程式時進行。

因此,您必須在更廣泛的條件下測試應用程式。

在Android6.0以下版本中,您可以合理假設,當應用程式完整執行時,即代表該應用程式具備其資訊清單中所宣告的所有權限。

而現在,無論API級別為何,使用者都能針對「任何」應用程式開啟或關閉權限。

建議您進行測試,以確保應用程式在各種權限情境中都能正確運作。

下列提示有助於在搭載API級別23以上版本的裝置上,找出權限相關的程式碼問題: 找出應用程式現有的權限和相關程式碼路徑。

針對所有受權限保護的服務和資料,測試使用者流程。

在授予或撤銷權限的各種組合情況下進行測試。

舉例來說,某個相機應用程式的資訊清單可能會列出CAMERA、READ_CONTACTS和ACCESS_FINE_LOCATION。

您應分別在這些權限開啟及關閉的情況下測試應用程式,以確保應用程式能夠妥善處理所有權限設定。

使用adb工具,透過指令列管理權限: 依群組列出權限和狀態:$adbshellpmlistpermissions-d-g 授予或撤銷一或多項權限:$adbshellpm[grant|revoke]... 針對會使用權限的服務進行應用程式分析。

其他資源 Android權限專用的質感設計指南 AndroidMarshmallow6.0:要求權限:這部影片說明Android執行階段權限模型,以及向使用者要求相關權限的正確方式。

說明應用程式需要權限的原因 不重複ID的最佳做法 Previous arrow_back Explainaccesstomoresensitiveinformation Next Permissionsusedonlyindefaulthandlers arrow_forward ContentandcodesamplesonthispagearesubjecttothelicensesdescribedintheContentLicense.JavaandOpenJDKaretrademarksorregisteredtrademarksofOracleand/oritsaffiliates. Lastupdated2022-05-14UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"translationIssue", "label":"Translationissue" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] Twitter Follow@AndroidDevonTwitter YouTube CheckoutAndroidDevelopersonYouTube LinkedIn ConnectwiththeAndroidDeveloperscommunityonLinkedIn MoreAndroid Android AndroidforEnterprise Security Source News Blog Podcasts Discover Gaming MachineLearning Privacy 5G AndroidDevices Largescreens WearOS AndroidTV Androidforcars AndroidThings ChromeOSdevices Releases Android11 Android10 Pie Oreo Nougat Marshmallow Lollipop KitKat DocumentationandDownloads AndroidStudioguide Developersguides APIreference DownloadStudio AndroidNDK Support Reportplatformbug Reportdocumentationbug GooglePlaysupport Joinresearchstudies Android Chrome Firebase GoogleCloudPlatform Allproducts Privacy License Brandguidelines Getnewsandtipsbyemail Subscribe Language English BahasaIndonesia Español–AméricaLatina Português–Brasil TiếngViệt 中文–简体 中文–繁體 日本語 한국어



請為這篇文章評分?