變更位置資訊設定 - Android Developers

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

長時間執行的作業完成後,將最快間隔設回較快的值。

取得目前的位置資訊設定. 連線至Google Play 服務和定位服務API 後,即可取得使用者 ... Platform AndroidStudio GooglePlay Jetpack Kotlin Docs Games English BahasaIndonesia Español–AméricaLatina Português–Brasil TiếngViệt 中文–简体 中文–繁體 日本語 한국어 Signin Documentation Overview Guides UIGuide Reference Samples Design&Quality Platform AndroidStudio GooglePlay Jetpack Kotlin Docs Overview Guides UIGuide Reference Samples Design&Quality Games AppBasics Introduction Buildyourfirstapp OverviewCreateanAndroidprojectRunyourappBuildasimpleuserinterfaceStartanotheractivity Appfundamentals Appresources OverviewHandleconfigurationchanges Localization LocalizeyourappTestyourappwithpseudolocalesUnicodeandinternationalizationsupportLanguageandlocaleresolutionPer-applanguagepreferencesComplexXMLresources Resourcetypes OverviewAnimationColorstatelistDrawableLayoutMenuStringStyleFontMoretypes Appmanifestfile Overview Devices Devicecompatibility OverviewScreencompatibilityoverviewSupportdifferentpixeldensitiesDeclarerestrictedscreensupport MultipleAPKsupport OverviewCreatemultipleAPKsfordifferentAPIlevelsCreatemultipleAPKsfordifferentscreensizesCreatemultipleAPKsfordifferentGLtexturesCreatemultipleAPKswithseveraldimensionsSupportdifferentlanguagesandculturesSupportdifferentplatformversionsFiltersonGooglePlay Largescreens—tablets,Chromebooks,foldables Getstartedwithlargescreens Largescreenready Multi-windowsupportMediaprojectionEnhancedletterboxingInputcompatibilityonlargescreens Largescreenoptimized SupportdifferentscreensizesMigrateyourUItoresponsivelayoutsNavigationforresponsiveUIsActivityembedding Largescreendifferentiated LearnaboutfoldablesMakeyourappfoldawareTestyourapponfoldablesLargescreencookbook Wear GetstartedPrinciplesofWearOSdevelopmentUpgradetothelatestversionofWearOSWearOSversusmobiledevelopmentWearOSuserinterface Gettingstarted WearOSdeveloperpathwayCreateandrunawearableappDebugaWearOSappCaptureWearUIscreenshots Overlays OverviewStandaloneappsAuthenticationRequestpermissionsDetectlocationPlayingaudioonwearablesAppearinRecentsandAppResume BuildingUIwithCompose UseJetpackComposeonWearOSComposeperformanceNavigationButtonsCardsChipsDialogsListsPageindicatorsPickersPositionindicatorProgressindicatorSlidersSteppersSwipetodismissTogglechipsTimetext BuildingUIwithViews BuildView-basedUIsonWearOSHandledifferentwatchshapesScreenoptionsCreatelistsNavigationExitfullscreenactivitiesonWearShowconfirmationsKeepyourappvisibleonWear Tilesandcomplications TilesoverviewGetstartedwithtilesUpdatetilesInteractwithtilesWatchfacecomplicationsExposedatatocomplications Notifications NotificationsonWearOSBridgingoptionsfornotificationsOngoingActivities Handlingdata SendandsyncdataonWearOSNetworkaccessandsynconWearOSAccesstheWearableDataLayerTransferassetsSendandreceivemessagesHandledatalayereventsSyncdataitemswiththeDataLayerAPI Userinput PhysicalbuttonsRotaryinputCreateinputmethodeditorsinWearVoice Healthservices OverviewActivedataandexercisePassivedataupdatesUsesyntheticdataprovidersEnhanceappcompatibility Design DesignprinciplesGettingstartedInteractiontypesScreenshapesNotificationsComplicationsTilesTilesdesignsystemOverlaysOngoingactivitiesConfirmationoverlayDisconnectionindicatorsPermissionmessagesSelectioncontrolsLaunchandlatencyNavigationPermissionsSigninHardwarebuttonsColorTypographyIconsDownloadsWearMaterialTheming Creatingwatchfaces OverviewDesignwatchfacesBuildawatchfaceserviceDrawwatchfacesAddingcomplicationstoawatchfaceCreatinginteractivewatchfacesProvideconfigurationactivitiesAddresscommonissuesImproveperformacewithhardwareaccelerationOptimizeperformanceandbatterylife WatchFaceStudio WatchFaceStudioKeyboardshortcutsManageaWatchFaceStudioprojectCreateawatchfacewithWatchFaceStudioBuildcomplicationsinWatchFaceStudioTagexpressionsLanguagesettingsAlways-oninWatchFaceStudioGyroeffectsBuildanduploadfromWatchFaceStudioTestyourwatchfaceFAQWearappqualityPackageWearOSappsDistributetoWearOSCreateWearOSappsforChinaWearOSreleasenotes AndroidTV Overview BuildTVApps OverviewGetstartedwithTVappsAndroidXTVlibrariesHandleTVhardwareManageTVcontrollersBuildTVlayoutsOn-screenkeyboardCreateTVnavigationBestpracticesfordrivingengagementonGoogleTV BuildTVplaybackapps Overview UIguidance&LeanbackAPI CreateacatalogbrowserProvideacardviewBuildadetailsviewUsetransportcontrolsPlaybackcontrolsonTVAmbientmodeAddaguidedstepIntroducefirst-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 OverviewUIeventsStateholdersandUIstateDomainlayer Datalayer OverviewOfflinefirstLearningpathway Modularization OverviewCommonpatterns 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 OverviewEnablinglinkstoappcontentVerifyapplinksCreateapplinksforinstantappsCreateswipeviewswithtabsusingViewPagerCreateswipeviewswithtabsusingViewPager2 Addsupportforbacknavigation CustombacknavigationPredictivebackgesture Dependencyinjection OverviewManualdependencyinjectionDependencyinjectionwithHiltHiltinmulti-moduleappsUseHiltwithotherJetpacklibrariesHilttestingguideHiltandDaggerannotationscheatsheet Dagger DaggerbasicsUsingDaggerinAndroidappsUsingDaggerinmulti-moduleapps AppStartup Userinterfaces BuildAndroiduserinterfaces Createbackward-compatibleUIs OverviewAbstractingthenewAPIsProxyingtothenewAPIsCreatinganimplementationwitholderAPIsUsingtheversion-awarecomponent Coretopics Appcompatibility OverviewCompatibilityframeworktoolsRestrictionsonnon-SDKinterfaces Interactwithotherapps OverviewSendingtheusertoanotherappGettingaresultfromanactivityAllowingotherappstostartyouractivity Packagevisibility OverviewKnowwhichpackagesarevisibleautomaticallyDeclarepackagevisibilityneedsFulfillcommonusecasesTestpackagevisibility Intentsandintentfilters OverviewCommonintents Audio&video Audio&videooverview Media3 Overview Gettingstarted UseamediasessiontomanageplaybackPlaymediainthebackground ExoPlayer ExoPlayerandMedia3ExoPlayertoMedia3mappingsMigrationguideMediacontrolsSupportedmediaformatsMediacodecs 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 OverviewMediaPhotopickerDocumentsandotherfilesDatasetsManageallfilesonastoragedeviceSavekey-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 Camera CamerabasicsChooseacameralibrary CameraX OverviewArchitectureConfiguration Usecases PreviewImagecaptureImageanalysisVideocapture Advancedtopics ExtensionsAPITransformoutputRotationsDevices Camera2 OverviewCameracapturesessionsandrequestsCameralensesandcapabilitiesUsemultiplecamerastreamssimultaneouslyCamerapreviewMulti-CameraAPIExtensionsAPI Camera(deprecated) OverviewTakephotosRecordvideosControlthecameraCameraAPI Sensors OverviewSensorsoverviewMotionsensorsPositionsensorsEnvironmentsensorsRawGNSSmeasurements Connectivity Overview CrossdeviceSDK OverviewGetstartedDevicediscoveryAPISecureconnectionAPISessionsAPITestanddebugAPIReference 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 RequestpermissiontoaccessnearbyWi-FidevicesWi-FiscanningoverviewWi-Fipeer-to-peerWi-FiAwareoverviewWi-FilocationwithRTTLocal-onlyhotspot Discoverandconnect OverviewUsenetworkservicediscoveryCreateP2PconnectionswithWi-FiDirectUseWi-FiDirectforservicediscoveryWi-FiEasyConnect Wi-Fiinfrastructure Wi-FiinfrastructureoverviewWi-FisuggestionAPIforinternetconnectivityWi-FiNetworkRequestAPIforpeer-to-peerconnectivityPasspointSavenetworksandPasspointconfigurations USB OverviewAccessoryoverviewHostoverviewUWBVPNSessioninitiationprotocoloverviewOpenMobileAPIreadersupport Renderscript OverviewAdvancedRenderScriptMigratefromRenderScript RuntimeAPIreference OverviewNumericaltypesObjecttypesConversionfunctionsMathematicalconstantsandfunctionsVectormathfunctionsMatrixfunctionsQuaternionfunctionsAtomicupdatefunctionsTimefunctionsandtypesAllocationdataaccessfunctionsObjectcharacteristicsfunctionsKernelinvocationfunctionsandtypesInput/outputfunctionsDebuggingfunctionsGraphicsfunctionsandtypesIndex Web-basedcontent OverviewBuildingwebappsinWebViewManagingWebViewobjectsLoadlocalcontentDarkenwebcontentUserprivacyinWebViewreportingSupportingdifferentscreensinwebappsDebuggingwebappsBestpracticesforwebappsTestingagainstfutureversionsofWebView 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 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 PackageSubmitUpdateIntegrityProtectionFAQGooglePlayInstant PlayasyouDownload OverviewBestpractices 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 Rendering OverviewReducingoverdrawPerformanceandviewhierarchiesAnalyzingwithprofileGPUrendering Slowrendering KeepingyourappresponsiveImprovinglayoutperformance Memory OverviewofmemorymanagementMemoryallocationamongpropertiesManageyourapp'smemoryProcessesandthreads Batteryandpower OptimizefordozeandappstandbyMonitorthebatterylevelandchargingstateMonitorconnectivitystatusandconnectionmeteringDetermingandmonitordockingstateandtypeProfilebatteryusagewithBatterystatsandBatteryHistorianAnalyzepowerusewithBatteryHistorianTestpower-relatedissuesBackgroundoptimizationsReduceappsizeHardwareacceleration 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 OverviewAndroid13Android12Android11Android10Android9Android8.0Android7.0Deviceadministration AndroidDevelopers Docs Guides 變更位置資訊設定 如果您的應用程式必須要求位置資訊或接收權限更新,裝置就必須啟用適當的系統設定,如GPS或掃描Wi-Fi。

您的應用程式不會直接啟用裝置的GPS等服務,而是指定所需的準確度/耗電量和偏好的更新間隔,而且裝置會自動對系統設定進行適當變更。

這些設定由LocationRequest資料物件定義。

本課程將說明如何使用設定用戶端來檢查已啟用的設定,並顯示「位置資訊設定」對話方塊,使用者只需在此輕觸一下即可更新設定。

設定定位服務 如要使用GooglePlay服務和整合式位置預測提供工具所提供的定位服務,請使用設定用戶端與應用程式連線,然後檢查目前的位置資訊設定,並提示使用者在需要時啟用必要的設定。

如果應用程式的功能會用到定位服務,必須要求位置存取權(視這些功能的用途而定)。

建立位置要求 如要儲存整合式位置預測提供工具的要求參數,請建立LocationRequest。

參數可判斷位置資訊要求的準確度。

如需所有可用位置資訊要求選項的詳細資料,請參閱LocationRequest類別參照。

本課程說明更新間隔、最快更新間隔和優先順序設定,如下所述: 更新間隔 setInterval() -此方法會設定應用程式接收位置資訊更新的偏好頻率(以毫秒為單位)。

請注意,為了最佳化電池用量,位置資訊更新速度可能比此速度快或慢,甚至完全沒有任何更新(例如裝置沒有連線時)。

最快更新間隔 setFastestInterval()-此方法會設定應用程式處理位置資訊更新的最快速度(以毫秒為單位)。

除非應用程式接收更新的速度比使用setInterval()中指定的速度更有優勢,否則您不需要呼叫此方法。

優先順序 setPriority()-此方法設定要求位置資訊的優先順序,向GooglePlay服務定位服務明確指出要使用的位置資訊來源。

支援下列值: PRIORITY_BALANCED_POWER_ACCURACY-使用此設定可要求將位置精確度設定為城市街區,準確度約為100公尺。

系統會將其視為概略準確度,因此耗電量可能會較低。

如果啟用此設定,定位服務可能會使用Wi-Fi和行動通信基地台定位。

但請注意,選擇位置提供者會受到許多其他因素影響,例如可用的來源。

PRIORITY_HIGH_ACCURACY-使用此設定即可要求最精確的位置。

啟用此設定,定位服務很可能會使用GPS來判斷位置。

PRIORITY_LOW_POWER-使用此設定可要求城市層級精確度,準確度約為10公里。

系統會將其視為概略準確度,因此耗電量可能會較低。

PRIORITY_NO_POWER-如果您需要不對耗電量造成影響,但希望在可用時接收位置更新通知,請使用此設定。

啟用此設定,您的應用程式不會觸發任何位置更新通知,但會接收其他應用程式觸發的位置資訊。

請按照此程式碼範例所示,建立位置要求並設定參數: Kotlin funcreateLocationRequest(){ vallocationRequest=LocationRequest.create()?.apply{ interval=10000 fastestInterval=5000 priority=LocationRequest.PRIORITY_HIGH_ACCURACY } } Java protectedvoidcreateLocationRequest(){ LocationRequestlocationRequest=LocationRequest.create(); locationRequest.setInterval(10000); locationRequest.setFastestInterval(5000); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } 設定PRIORITY_HIGH_ACCURACY的優先順序,結合您在應用程式資訊清單中定義的ACCESS_FINE_LOCATION權限設定,以及5000毫秒(5秒)的快速更新間隔,即可使整合式位置預測提供工具傳回的誤差範圍不到數英尺的位置更新通知。

此方法適用於即時顯示位置資訊的對應應用程式。

效能提示:如果您的應用程式在接收位置更新通知後存取網路或進行其他長時間執行的作業,請將最快間隔調整為較低的值。

透過這項調整,可避免應用程式接收無法使用的更新。

長時間執行的作業完成後,將最快間隔設回較快的值。

取得目前的位置資訊設定 連線至GooglePlay服務和定位服務API後,即可取得使用者裝置目前的位置資訊設定。

如要執行此操作,請建立LocationSettingsRequest.Builder,然後新增一個或多個位置要求。

下列程式碼片段顯示了如何新增在上一步驟中建立的位置要求: Kotlin valbuilder=LocationSettingsRequest.Builder() .addLocationRequest(locationRequest) Java LocationSettingsRequest.Builderbuilder=newLocationSettingsRequest.Builder() .addLocationRequest(locationRequest); 接著,檢查是否符合目前的位置資訊設定: Kotlin valbuilder=LocationSettingsRequest.Builder() //... valclient:SettingsClient=LocationServices.getSettingsClient(this) valtask:Task=client.checkLocationSettings(builder.build()) Java LocationSettingsRequest.Builderbuilder=newLocationSettingsRequest.Builder(); //... SettingsClientclient=LocationServices.getSettingsClient(this); Tasktask=client.checkLocationSettings(builder.build()); Task完成後,應用程式會查看LocationSettingsResponse物件中的狀態碼,藉此檢查位置資訊設定。

如要進一步瞭解相關位置資訊設定目前的狀態,應用程式可以呼叫LocationSettingsResponse物件的getLocationSettingsStates()方法。

提示使用者變更位置資訊設定 如要判斷位置資訊設定是否適合地區要求,請將OnFailureListener新增至可驗證位置資訊設定的Task物件。

接著,請檢查傳遞給onFailure()方法的Exception物件是否為ResolvableApiException類別的執行個體,這表示必須變更設定。

然後,顯示對話方塊,提示使用者呼叫startResolutionForResult(),取得修改位置資訊設定的權限。

下列程式碼片段指出如何判斷使用者的位置資訊設定是否允許定位服務建立LocationRequest,以及如何向使用者要求權限,以視需要變更位置資訊設定: Kotlin task.addOnSuccessListener{locationSettingsResponse-> //Alllocationsettingsaresatisfied.Theclientcaninitialize //locationrequestshere. //... } task.addOnFailureListener{exception-> if(exceptionisResolvableApiException){ //Locationsettingsarenotsatisfied,butthiscanbefixed //byshowingtheuseradialog. try{ //ShowthedialogbycallingstartResolutionForResult(), //andchecktheresultinonActivityResult(). exception.startResolutionForResult(this@MainActivity, REQUEST_CHECK_SETTINGS) }catch(sendEx:IntentSender.SendIntentException){ //Ignoretheerror. } } } Java task.addOnSuccessListener(this,newOnSuccessListener(){ @Override publicvoidonSuccess(LocationSettingsResponselocationSettingsResponse){ //Alllocationsettingsaresatisfied.Theclientcaninitialize //locationrequestshere. //... } }); task.addOnFailureListener(this,newOnFailureListener(){ @Override publicvoidonFailure(@NonNullExceptione){ if(einstanceofResolvableApiException){ //Locationsettingsarenotsatisfied,butthiscanbefixed //byshowingtheuseradialog. try{ //ShowthedialogbycallingstartResolutionForResult(), //andchecktheresultinonActivityResult(). ResolvableApiExceptionresolvable=(ResolvableApiException)e; resolvable.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); }catch(IntentSender.SendIntentExceptionsendEx){ //Ignoretheerror. } } } }); 在下一堂課接收位置更新通知中,您會瞭解如何接收定期位置更新通知。

Previous arrow_back Getthelastknownlocation Next Requestlocationupdates arrow_forward ContentandcodesamplesonthispagearesubjecttothelicensesdescribedintheContentLicense.JavaandOpenJDKaretrademarksorregisteredtrademarksofOracleand/oritsaffiliates. Lastupdated2022-05-04UTC. [{ "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 English BahasaIndonesia Español–AméricaLatina Português–Brasil TiếngViệt 中文–简体 中文–繁體 日本語 한국어



請為這篇文章評分?