在Android Kotlin应用程序中如何处理大数目?

我有一个简单的Android应用程序,可以计算一个数字的阶乘。 问题是,每当我输入一个数字大于5位数的应用程序停止。

logcat的:

Skipped 32 frames! The application may be doing too much work on its main thread. Background concurrent copying GC freed 131318(3MB) AllocSpace objects, 0(0B) LOS objects, 49% free, 4MB/8MB, paused 80us total 194.279ms 

科特林代码:

 package com.example.paciu.factorial import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* import java.math.BigInteger class MainActivity : AppCompatActivity() { tailrec fun tail_recursion_factorial(n: BigInteger, factorialOfN: BigInteger = BigInteger.valueOf(2)): BigInteger { return when (n) { BigInteger.ZERO -> BigInteger.ONE BigInteger.ONE -> BigInteger.ONE BigInteger.valueOf(2) -> factorialOfN else -> { tail_recursion_factorial(n.minus(BigInteger.ONE), n.times(factorialOfN)) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnFact.setOnClickListener { var n = editText.text.toString() try { when { BigInteger(n) < BigInteger.ZERO -> textView.text = "Sorry bro! Can't do a factorial to a negative number." BigInteger(n) >= BigInteger.ZERO -> { textView.text = "$n! is ${tail_recursion_factorial(BigInteger(n))}" System.gc() } } } catch (e: NumberFormatException) { textView.text = "Sorry bro! Can't do that ..." } } } } 

我是这个领域的新手,所以任何人都可以帮助我理解为什么会发生这种情况?

你的信息可能不是一个真正的错误,但明确说明原因。

所谓的UI线程是用来渲染帧的显示。 如果你在做这些繁重的工作,你会阻止这个渲染,你的应用暂停。

因此,不必在UI-Thread上做所有事情,而必须在不同的线程上安排工作,并将UI更新传回给UI-Thread。

实施这种方式有不同的可能模式。

  • AsyncTask
  • HandlerThread
  • Kotlin协程
  • RxJava

只要看看,自己试试看。 你只需要知道只更新UI线程的视图属性。 否则,你会再次以不同的原因崩溃。

您的代码在UI 线程上运行,并且您的代码可能会花费时间限制在该线程上运行,而不会返回到系统。 你的代码超过了这个限制,结果你的应用程序被认为是停滞的,并被系统杀死,因为在“应用程序不响应”对话框中。 为了防止这种情况发生,您必须将您的计算移至单独的线程,即。 通过使用Kotlin的协程或AsyncTask左右。

一般来说,你需要阅读保持你的应用程序响应和相关的文档章节。