Detect and diagnose crashes | Android Developers

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

The first step to fix a crash is to identify the place where it happens. You can use the stack trace available in the report details if you ... Platform AndroidStudio GooglePlay Jetpack Kotlin Docs Games Language English BahasaIndonesia Español–AméricaLatina Português–Brasil 中文–简体 日本語 한국어 Signin Games Overview Guides AndroidGameDevelopmentKit GamesonGooglePlay GamesonPC Platform AndroidStudio GooglePlay Jetpack Kotlin Docs Games Overview Guides AndroidGameDevelopmentKit GamesonGooglePlay GamesonPC Introduction Newdeveloperguide Developerpreviews Toolsandlibraries Overview AndroidGameDevelopmentKit(AGDK) OverviewLibrariesDownloadReleasenotes AndroidStudio AndroidGameDevelopmentExtensionforVisualStudio OverviewQuickstartConfigureaprojectDebuggerMeasureappperformanceModifybuild.gradlefilesforAndroidStudioSamplesReleasenotes AndroidGPUInspector OverviewQuickstartSupporteddevices Systemprofiling OverviewViewasystemprofileGPUperformancecounters Analyzeasystemprofile FrameprocessingtimesMemoryefficiencyTexturememorybandwidthusageVertexmemorybandwidthusageThreadscheduling Frameprofiling Overview Analyzeaframeprofile MostexpensiverenderpassesVertexformatsShaderperformance FrameProfilerUI PerformancepaneCommandspaneFramebufferpaneGeometrypaneReportpaneShaderpaneMemorypaneStatepaneTexturespaneTexturepanePipelineviewpaneSupportedVulkanextensionsTroubleshoot AndroidPerformanceTuner MemoryAdviceAPI OverviewGetstarted Developwithgameengines Useprebuiltorturnkeygameengines Overview DevelopwithDefold InstallandconfigureprojectsforAndroidSupportmultipleformfactorsandscreensizesExporttoAndroid DevelopwithGodot InstallandconfigureprojectsforAndroidGodotrendereroptionsSupportmultipleformfactorsandscreensizesExporttoAndroid DevelopwithUnity OverviewCreateanAndroidAppBundlewithUnityIntegratePlayAssetDeliveryUnityLightinginMobileGames UseAndroidPerformanceTuner OverviewEnabletheAPIIntegratethepluginInitializethelibraryandverifyoperationDefineannotations,fidelityparameters,andqualitylevelsAddloadingtimerecordingfunctionsRunthemonitorappReviewandpublishTroubleshootcommonerrorsReferenceDevelopwithUnrealRequestinguserpermissionsSecureyourgame Customizeorportgameengines Overview Gettingstarted IntegrateGameActivityConfiguregraphicsUnderstandAndroidgameloops Processinputevents AddtouchsupportSupporttextinput Supportgamecontrollers OverviewUsethegamecontrollerlibraryUsecustomcontrollerdevicemappingsAddmousesupportSupportsensorinput Achieveproperframepacing Overview FramepacinginOpenGLES IntegrateUpdateyourbuildsettingsAddframepacingfunctionsVerifyframepacingimprovement FramepacinginVulkan IntegrateUpdateyourbuildsettingsAddframepacingfunctionsVerifyframepacingimprovementReference IntegrateAndroidPerformanceTuner OverviewRunthedemoappEnabletheAPIUpdateyourbuildsettingsDefineannotations,fidelityparameters,andsettingsAddframetimingfunctionsAddloadingtimerecordingfunctionsValidate,package,andpublishtheAPKTroubleshootcommonerrorsAdvancedusageReference Outputaudio OverviewUpdatebuildsettingsUseOboeCodesamplesFullOboeguide Managememory OverviewDebugnativememoryuseDeliverassetsDetectanddiagnosecrashes Optimizationandbestpractices Improvegameperformance Reducegamesize Improvedeviceavailability Support64-bitarchitecturesSupportallscreens GameMode OverviewOptimizewithGameModeAPIGameModeinterventions VulkanandOpenGL 3DassetoptimizationVulkanPrerotationVertexdatamanagement Gameservicesanddistribution Overview GooglePlayGamesServices OverviewGetstartedDownloads Features AchievementsLeaderboardsEventsSavedgamesFriendsSign-in PlayConsolesetup SetupPlayGamesServicesEnablefeaturesTestandpublish Developmenttasks C++ Getstarted Android GetstartedSign-inEnableserver-sideaccess Addfeatures AchievementsLeaderboardsFriendsSavedgamesEventsPlayerstatsLoggingTroubleshooting PublishingAPI OverviewGetstartedUploadimagesManagementAPI Requirementsandguidelines QualitychecklistBrandingguidelinesQuotaandratelimitsDatadisclosurerequirementsTermsofservice GooglePlayGamesforPC OverviewGetstarted Setupyourgame PCcompatibilityGraphicsconfiguration Deviceinput Setupinput InputSDK OverviewQuickstart Continuity OverviewContinuityrequirementsVerifyingrequirementsExistingidentitysolutionsUsetheemulatorTestonChromeOS Publishanddeploy PackageSubmitFAQ GooglePlayInstant Playasyoudownload AndroidDevelopers Games Guides Detectanddiagnosecrashes AnAndroidappcrasheswheneverthere’sanunexpectedexitcausedbyan unhandledexceptionorsignal.AnappthatiswrittenusingJavaorKotlin crashesifitthrowsanunhandledexception,representedbythe Throwableclass.An appthatiswrittenusingnative-codelanguagescrashesifthere’sanunhandled signal,suchasSIGSEGV,duringitsexecution. Whenanappcrashes,Androidterminatestheapp'sprocessanddisplaysadialog tolettheuserknowthattheapphasstopped,asshowninfigure1. Figure1.AnappcrashonanAndroiddevice Anappdoesn’tneedtoberunningintheforegroundforittocrash.Anyapp component,evencomponentslikebroadcastreceiversorcontentprovidersthat arerunninginthebackground,cancauseanapptocrash.Thesecrashesare oftenconfusingforusersbecausetheywerenotactivelyengagingwithyourapp. Ifyourappisexperiencingcrashes,youcanusetheguidanceinthispageto diagnoseandfixtheproblem. Detecttheproblem Youmaynotalwaysknowthatyourusersareexperiencinganinordinatenumberof crasheswithyourapp.Ifyouhavealreadypublishedyourapp,Androidvitals canhelpmakeyouawareoftheproblem. Androidvitals Androidvitalscanhelpimproveyourapp'sperformancebyalertingyou,viathe Play Console,whenyourappisexhibitingexcessivecrashes. Androidvitalsconsiderscrashesexcessivewhenanapp: Exhibitsatleastonecrashinatleast1.09%ofitsdailysessions. Exhibitstwoormorecrashesinatleast0.18%ofitsdailysessions. Adailysessionreferstoadayinwhichyourappwasused. ForinformationonhowGooglePlaycollectsAndroidvitalsdata,seethe PlayConsoledocumentation. Afteryoulearnthatyourappissufferingfromtoomanycrashes,the nextstepistodiagnosethem. Diagnosethecrashes Solvingcrashescanbedifficult.However,ifyoucanidentifytherootcauseof thecrash,mostlikelyyoucanfindasolutiontoit. Therearemanysituationsthatcancauseacrashinyourapp.Somereasonsare obvious,likecheckingforanullvalueoremptystring,butothersaremore subtle,likepassinginvalidargumentstoanAPIorevencomplexmultithreaded interactions. CrashesonAndroidproduceastacktrace,whichisasnapshotofthesequenceof nestedfunctionscalledinyourprogramuptothemomentitcrashed.Youcan viewcrashstacktracesin Androidvitals. Readingastacktrace Thefirststeptofixacrashistoidentifytheplacewhereithappens.Youcan usethestacktraceavailableinthereportdetailsifyouareusingPlay Consoleortheoutputofthelogcattool.Ifyou don’thaveastacktraceavailable,youshouldlocallyreproducethecrash, eitherbymanuallytestingtheapporbyreachingouttoaffectedusers,and reproduceitwhileusinglogcat. ThefollowingtraceshowsanexampleofacrashonanappwrittenusingtheJava programminglanguage: ---------beginningofcrash AndroidRuntime:FATALEXCEPTION:main Process:com.android.developer.crashsample,PID:3686 java.lang.NullPointerException:crashsample atcom.android.developer.crashsample.MainActivity$1.onClick(MainActivity.java:27) atandroid.view.View.performClick(View.java:6134) atandroid.view.View$PerformClick.run(View.java:23965) atandroid.os.Handler.handleCallback(Handler.java:751) atandroid.os.Handler.dispatchMessage(Handler.java:95) atandroid.os.Looper.loop(Looper.java:156) atandroid.app.ActivityThread.main(ActivityThread.java:6440) atjava.lang.reflect.Method.invoke(NativeMethod) atcom.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) atcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:746) ---------beginningofsystem Astacktraceshowstwopiecesofinformationthatarecriticaltodebugginga crash: Thetypeofexceptionthrown. Thesectionofcodewheretheexceptionisthrown. Thetypeofexceptionthrownisusuallyaverystronghintastowhatwent wrong.Lookatwhetheritisan IOException,an OutOfMemoryError, orsomethingelse,andfindthedocumentationabouttheexceptionclass. Theclass,method,file,andlinenumberofthesourcefilewheretheexception isthrownisshownonthesecondlineofastacktrace.Foreachfunctionthat wascalled,anotherlineshowstheprecedingcallsite(calledastackframe). Bywalkingupthestackandexaminingthecode,youmayfindaplacethatis passinganincorrectvalue.Ifyourcodedoesn’tappearinthestacktrace,it islikelythatsomewhere,youpassedaninvalidparameterintoanasynchronous operation.Youcanoftenfigureoutwhathappenedbyexaminingeachlineofthe stacktrace,findinganyAPIclassesthatyouused,andconfirmingthatthe parametersyoupassedwerecorrect,andthatyoucalleditfromaplacethatis allowed. StacktracesforappswithCandC++codeworkmuchthesameway. ************************************************ Buildfingerprint:'google/foo/bar:10/123.456/78910:user/release-keys' ABI:'arm64' Timestamp:2020-02-1611:16:31+0100 pid:8288,tid:8288,name:com.example.testapp>>>com.example.testapp<<< uid:1010332 signal11(SIGSEGV),code1(SEGV_MAPERR),faultaddr0x0 Cause:nullpointerdereference x00000007da81396c0x10000007fc91522d4x20000000000000001x3000000000000206e x40000007da8087000x50000007fc9152310x60000007d209c6c68x70000007da8087000 x80000000000000000x90000007cba01b660x100000000000430000x110000007d80000000 x120000000000000060x130000000023fafc10x140000000000000006x15ffffffffffffffff x160000007cba01b618x170000007da44c88c0x180000007da943c000x190000007da8087000 x200000000000000000x210000007da8087000x220000007fc9152540x230000007d17982d6b x240000000000000004x250000007da823c020x260000007da80870b0x270000000000000001 x280000007fc91522d0x290000007fc91522a0 sp0000007fc9152290lr0000007d22d4e354pc0000007cba01b640 backtrace: #00pc0000000000042f89/data/app/com.example.testapp/lib/arm64/libexample.so(com::example::Crasher::crash()const) #01pc0000000000000640/data/app/com.example.testapp/lib/arm64/libexample.so(com::example::runCrashThread()) #02pc0000000000065a3b/system/lib/libc.so(__pthread_start(void*)) #03pc000000000001e4fd/system/lib/libc.so(__start_thread) Ifyoudon'tseeclassandfunction-levelinformationinnativestacktraces, youmayneedto generateanativedebugsymbolsfile anduploadittotheGooglePlayConsole.Formoreinformation,see Deobfuscatecrashstacktraces. Forgeneralinformationonnativecrashes,see Diagnosingnativecrashes. Tipsforreproducingacrash It’spossiblethatyoucan’tquitereproducetheproblemjustbystartingan emulatororconnectingyourdevicetoyourcomputer.Developmentenvironments tendtohavemoreresources,suchasbandwidth,memory,andstorage.Usethe typeofexceptiontodeterminewhatcouldbetheresourcethatisscarce,or findacorrelationbetweentheversionofAndroid,devicetypeoryourapp’s version. Memoryerrors Ifyouhavean OutOfMemoryError, thenyoucouldcreateanemulatorwithlowmemorycapacitytotestwith.Figure 2showstheAVDmanagersettingswhereyoucancontroltheamountofmemoryon thedevice. Figure2.MemorysettingonAVDmanager Networkingexceptions SinceusersfrequentlymoveinandoutofmobileorWiFinetworkcoverage,inan applicationnetworkexceptionsusuallyshouldnotbetreatedaserrors,but ratherasnormaloperatingconditionsthathappenunexpectedly. Ifyouneedtoreproduceanetworkexception,suchasan UnknownHostException, thentryturningonairplanemodewhileyourapplicationattemptstousethe network. Anotheroptionistoreducethequalityofthenetworkintheemulatorby choosinganetworkspeedemulationand/oranetworkdelay.Youcanusethe SpeedandLatencysettingsonAVDmanager,oryoucanstarttheemulator withthe-netdelayand-netspeedflags,asshowninthefollowing command-lineexample: emulator-avd[your-avd-image]-netdelay20000-netspeedgsm Thisexamplesetsadelayof20secondsonallnetworkrequestsandanupload anddownloadspeedof14.4Kbps.Formoreinformationoncommand-lineoptions fortheemulator,see Starttheemulatorfromthecommandline. Readingwithlogcat Onceyouareablehavethestepstoreproducethecrash,youcanuseatoollike logcattogetmore information. Thelogcatoutputwillshowyouwhatotherlogmessagesyouhaveprinted,along withothersfromthesystem.Don’tforgettoturnoffanyextra Logstatementsthatyou haveaddedbecauseprintingthemwastesCPUandbatterywhileyourappis running. Preventcrashescausedbynullpointerexceptions Nullpointerexceptions(identifiedbytheruntimeerrortype NullPointerException)occurwhenyou'retryingtoaccessanobjectthatis null,typicallybyinvokingitsmethodsoraccessingitsmembers.Nullpointer exceptionsarethelargestcauseofappcrashesonGooglePlay.Thepurposeof nullistosignifythattheobjectismissing-forexample,ithasn'tbeen createdorassignedyet.Toavoidnullpointerexceptions,youneedtomakesure thattheobjectreferencesyou'reworkingwitharenon-nullbeforecalling methodsonthemortryingtoaccesstheirmembers.Iftheobjectreferenceis null,handlethiscasewell(forexample,exitfromamethodbeforeperforming anyoperationsontheobjectreferenceandwriteinformationtoadebuglog). Becauseyoudon'twanttohavenullchecksforeveryparameterofeverymethod called,youcanrelyontheIDEoronthetypeoftheobjecttosignify nullability. Javaprogramminglanguage ThefollowingsectionsapplytotheJavaprogramminglanguage. Compiletimewarnings Annotateyourmethods'parametersandreturnvalueswith @Nullableand @NonNulltoreceivecompiletime warningsfromtheIDE.Thesewarningspromptyoutoexpectanullableobject: Thesenullchecksareforobjectsthatyouknowcouldbenull.Anexceptionona @NonNullobjectisanindicationofanerrorinyourcodethatneedstobe addressed. Compiletimeerrors Becausenullabilityshouldbemeaningful,youcanembeditinthetypesyouuse sothatthereisacompiletimecheckfornull.Ifyouknowanobjectcanbe nullandthatnullabilityshouldbehandled,youcouldwrapitinanobjectlike Optional. Youshouldalwaysprefertypesthatconveynullability. Kotlin InKotlin, nullability ispartofthetypesystem.Forexample,avariableneedstobedeclaredfrom thebeginningasnullableornon-nullable.Nullabletypesaremarkedwitha?: //non-null vars:String="Hello" //null vars:String?="Hello" Non-nullablevariablescannotbeassignedanullvalueandnullablevariables needtobecheckedfornullabilitybeforebeingusedasnon-null. Ifyoudon'twanttocheckfornullexplicitly,youcanusethe?.safecall operator: vallength:Int?=string?.length//lengthisanullableint //ifstringisnull,thenlengthisnull Asabestpractice,makesureyouaddressthenullcaseforanullableobject, oryourappcouldgetintounexpectedstates.Ifyourapplicationwon'tcrash anymorewithNullPointerException,youwon'tknowthattheseerrorsexist. Thefollowingaresomewaystocheckfornull: ifchecks vallength=if(string!=null)string.lengthelse0 Duetosmart-castandthenullcheck,theKotlincompilerknowsthatthe stringvalueisnon-nullsoitallowsyoutousethereferencedirectly, withouttheneedforthesafecalloperator. ?:Elvisoperator Thisoperatorallowsyoutostate"iftheobjectisnon-null,returnthe object;otherwise,returnsomethingelse". vallength=string?.length?:0 YoucanstillgetaNullPointerExceptioninKotlin.Thefollowingarethemost commonsituations: Whenyou'reexplicitlythrowingaNullPointerException. Whenyou'reusingthe nullassertion!!operator. Thisoperatorconvertsanyvaluetoanon-nulltype,throwing NullPointerExceptionifthevalueisnull. Whenaccessinganullreferenceofaplatformtype. Platformtypes PlatformtypesareobjectdeclarationscomingfromJava. Thesetypesarespecially-treated; nullchecksarenotasenforced,sothenon-nullguaranteeisthesameasin Java.Whenyouaccessaplatformtypereference,Kotlindoesnotcreatecompile timeerrorsbutthesereferencescanleadtoruntimeerrors.Seethefollowing examplefromtheKotlindocumentation: vallist=ArrayList()//non-null(constructorresult)list.add("Item") valsize=list.size//non-null(primitiveint)valitem=list[0]//platform typeinferred(ordinaryJavaobject)item.substring(1)//allowed,maythrowan //exceptionifitem==null KotlinreliesontypeinferencewhenaplatformvalueisassignedtoaKotlin variable,oryoucandefinewhattypetoexpect.Thebestwaytoensurethe correctnullabilitystateofareferencecomingfromJavaistousenullability annotations(forexample,@Nullable)inyourJavacode.TheKotlincompiler willrepresentthesereferencesasactualnullableornon-nullabletypes,notas platformtypes. JavaJetpackAPIshavebeenannotatedwith@Nullableor@NonNullasneeded, andasimilarapproachhasbeentakeninthe Android11SDK. TypescomingfromthisSDK,thatareusedinKotlin,willberepresentedas correctnullableornon-nullabletypes. BecauseofKotlin'stypesystem,we'veseenappshaveamajorreductionin NullPointerExceptioncrashes.Forexample,theGoogleHomeappsawa30% reductionincrashescausedbynullpointerexceptionsduringtheyearthatit migratednewfeaturedevelopmenttoKotlin. ContentandcodesamplesonthispagearesubjecttothelicensesdescribedintheContentLicense.JavaandOpenJDKaretrademarksorregisteredtrademarksofOracleand/oritsaffiliates. Lastupdated2021-04-07UTC. [{ "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":"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 中文–简体 日本語 한국어



請為這篇文章評分?