Detect and diagnose crashes | Android Developers
文章推薦指數: 80 %
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
延伸文章資訊
- 1Capture and read bug reports | Android Developers
A bug report contains device logs, stack traces, and other diagnostic information to help ... Goo...
- 2How to get crash logs on Android? - Keepsafe Support
How to get crash logs on Android? · 1. Activate developer options on your device · 2. Enable Deve...
- 3Detect and diagnose crashes | Android Developers
The first step to fix a crash is to identify the place where it happens. You can use the stack tr...
- 4How to make sense of Android crash logs | Bugsnag Blog
If an app hasn't got a crash reporting SDK installed, then the next best method for retrieving cr...
- 5How to get Android crash logs? - Stack Overflow
1) Plug in Phone through USB (w/ Developer Debugging options enabled) · 2) Open Terminal and Navi...