本篇內(nèi)容主要講解“Android中如何處理后臺(tái)崩潰”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Android中如何處理后臺(tái)崩潰”吧!
成都創(chuàng)新互聯(lián)專注于峨山縣企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站開發(fā),商城網(wǎng)站制作。峨山縣網(wǎng)站建設(shè)公司,為峨山縣等地區(qū)提供建站服務(wù)。全流程專業(yè)公司,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)原理其實(shí)蠻簡單的。
檢測(cè)是否為后臺(tái)
如果是后臺(tái)則殺掉該進(jìn)程,否則執(zhí)行默認(rèn)的崩潰處理
檢測(cè)是否為后臺(tái),這里我們以進(jìn)程中Activity的數(shù)量作為判斷標(biāo)準(zhǔn)
當(dāng)activity onStart時(shí)activityCount自增
當(dāng)Activity onStop時(shí)activityCount自減
當(dāng)activityCount為0,我們則認(rèn)為應(yīng)用處于后臺(tái)狀態(tài)
具體實(shí)現(xiàn)如下:
object ActivityLifecycleCallbackImp: Application.ActivityLifecycleCallbacks { var activityCount: Int = 0 override fun onActivityPaused(activity: Activity?) { } override fun onActivityResumed(activity: Activity?) { } override fun onActivityStarted(activity: Activity?) { activityCount ++ } override fun onActivityDestroyed(activity: Activity?) { } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { activityCount-- } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { } }
在Application中進(jìn)行注冊(cè):
class MyApplication : Application() { override fun onCreate() { super.onCreate() registerActivityLifecycleCallbacks(ActivityLifecycleCallbackImp) } }
剩下的就是設(shè)置一個(gè)自定義的未捕獲異常處理處理器:
val defaultHandler = Thread.getDefaultUncaughtExceptionHandler() Thread.setDefaultUncaughtExceptionHandler { thread, exception -> exception.printStackTrace() val isBackground = ActivityLifecycleCallbackImp.activityCount == 0 if (isBackground) { Log.d("MyApplication", "isBackground just kill the process without annoying users") android.os.Process.killProcess(android.os.Process.myPid()) } else { defaultHandler.uncaughtException(thread, exception) } }
到此,相信大家對(duì)“Android中如何處理后臺(tái)崩潰”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)建站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!