Android AsyncTask 不运行

Posted

技术标签:

【中文标题】Android AsyncTask 不运行【英文标题】:Android AsyncTask Doesn't Run 【发布时间】:2019-02-08 21:14:22 【问题描述】:

我在 Kotlin 中有一个 AsyncTask 类,它在被调用时并没有开始运行。 AsyncTask 应该从特定 URL 下载 JSON 数据。 doInBackground 方法从未启动,也没有任何反应。

onCreate()

override fun onCreate(savedInstanceState: Bundle?) 
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // TODO Remove After
//        loadData()
    getDataFromUrl()

    // Set adapter
    adapter = CardAdapter(listOfCard, this)
    lvCards.adapter = adapter

我的 getDataFromUrl(),其中调用了 AsyncTask:

private fun getDataFromUrl() 
    val url = "https://pay-app-api.herokuapp.com/card/user/1"
    mAsyncTask().execute(url)

AsyncTask 内部类:

inner class mAsyncTask: AsyncTask<String, String, String>() 

    override fun onPreExecute() 
        Log.d(TAG, "Pre Execute")
        super.onPreExecute()
    

    override fun doInBackground(vararg params: String?): String? 
        try 
            // Connect to URL
            val url = URL(params[0])
            val urlConnect = url.openConnection() as HttpURLConnection
//                urlConnect.connectTimeout = 5000

            // Read Data from URL
            val mInputString = 
            convertStreamToString(urlConnect.inputStream)

            publishProgress(mInputString)

         catch (ex: Exception) 

        return ""
    

    override fun onProgressUpdate(vararg values: String?) 

        try 
            val json = JSONObject(values[0])
            tvJsonTest.text = "Downloaded"
            Log.d(TAG, json.toString())
            System.out.print("Downloading...")
         catch (ex: Exception) 

//            super.onProgressUpdate(*values)
    

和 LogCat 日志:

09-03 22:44:44.337 2647-2647/? E/Zygote: v2
09-03 22:44:44.337 2647-2647/? I/libpersona: KNOX_SDCARD checking this for 
10228
KNOX_SDCARD not a persona
09-03 22:44:44.342 2647-2647/? E/Zygote: accessInfo : 0
09-03 22:44:44.344 2647-2647/? W/SELinux: SELinux         
selinux_android_compute_policy_index : Policy Index[2],  Con:u:r:zygote:s0     
RAM:SEPF_SECMOBILE_7.1.1_0003, [-1 -1 -1 -1 0 1]
09-03 22:44:44.347 2647-2647/? I/SELinux: SELinux: seapp_context_lookup: 
seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.makro123.payapp 
09-03 22:44:44.354 2647-2647/? I/art: Late-enabling -Xcheck:jni
09-03 22:44:44.717 2647-2647/com.example.makro123.payapp W/System: 
ClassLoader referenced unknown path: 
/data/app/com.example.makro123.payapp-1/lib/arm
09-03 22:44:44.751 2647-2647/com.example.makro123.payapp I/InstantRun: 
starting instant run server: is main process
09-03 22:44:44.885 2647-2647/com.example.makro123.payapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
09-03 22:44:45.045 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.047 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.052 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.064 2647-2647/com.example.makro123.payapp D/MainActivity: Pre Execute
09-03 22:44:45.100 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: ThreadedRenderer.create() translucent=false
09-03 22:44:45.105 2647-2647/com.example.makro123.payapp D/InputTransport: Input channel constructed: fd=74
09-03 22:44:45.107 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: setView = DecorView@ec37ba4[MainActivity] touchMode=true
09-03 22:44:45.110 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: dispatchAttachedToWindow
09-03 22:44:45.149 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][720,1280] result=0x27 surface=isValid=true -1863970816 surfaceGenerationChanged=true
    mHardwareRenderer.initialize() mSurface=isValid=true -1863970816 hwInitialized=true
09-03 22:44:45.151 2647-2686/com.example.makro123.payapp I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8916_32_LA.BR.1.2.9_RB1__release_AU (I750f7f2fa6)
    OpenGL ES Shader Compiler Version: XE031.09.00.03
    Build Date: 02/18/17 Sat
    Local Branch: 
    Remote Branch: quic/LA.BR.1.2.9_rb1.12
    Local Patches: NONE
    Reconstruct Branch: NOTHING
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp I/OpenGLRenderer: Initialized EGL, version 1.4
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp D/OpenGLRenderer: Swap behavior 1
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp W/Adreno-EGL: <qeglDrvAPI_eglCreateContext:2475>: EGL_BAD_ATTRIBUTE
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp I/OpenGLRenderer: KHR Debugger is Disabled - EGL_BAD_ATTRIBUTE
09-03 22:44:45.159 2647-2647/com.example.makro123.payapp D/AbsListView:  in onLayout changed 
09-03 22:44:45.208 2647-2647/com.example.makro123.payapp W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
09-03 22:44:45.227 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.233 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.257 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
    MSG_WINDOW_FOCUS_CHANGED 1
    mHardwareRenderer.initializeIfNeeded()#2 mSurface=isValid=true -1863970816
09-03 22:44:45.259 2647-2647/com.example.makro123.payapp V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@7159272 nm : com.example.makro123.payapp ic=null
09-03 22:44:45.259 2647-2647/com.example.makro123.payapp I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
09-03 22:44:45.270 2647-2681/com.example.makro123.payapp D/InputTransport: Input channel constructed: fd=78
09-03 22:44:45.282 2647-2647/com.example.makro123.payapp V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@cfa46c3 nm : com.example.makro123.payapp ic=null

【问题讨论】:

尝试删除 Toast.makeText(applicationContext, "Async Task", Toast.LENGTH_SHORT).show() 你有什么理由不使用协程? 【参考方案1】:

doInBackground 中的这一行会停止所有执行并抛出 RuntimeException

Toast.makeText(applicationContext, "Async Task", Toast.LENGTH_SHORT).show()

原因是这条线需要在主线程 (UI) 上运行,否则它只是神秘地停止所有进一步的执行并崩溃 - 静默!

之所以静默崩溃,是因为你“吃掉”了doInBackground末尾的异常。

如果你没有“吃掉”异常,你会得到这样的异常:

Caused by: java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()

如果你想调用一些需要在 UI 线程上运行的代码,你应该在onProgressUpdate 中调用它——这在AsyncTask 的文档中也有说明。

onPreExecuteonPostExecute 也将在 UI 线程上调用,因此可以安全地更改 UI 中的内容或在那里显示 Toast

【讨论】:

正是这个。 @marko-k 记得只从主线程更新 UI。 嗨,达尔文,我删除了那行(吐司)。但是我仍然遇到数据未下载的问题。 doInBackground 没有做它应该做的事情。 @MarkoK 如果答案解决了您最初的问题(确实如此),我建议您将答案标记为正确并打开另一个问题,询问为什么没有下载您的数据。如果我们继续这个问题,那么下一个来这里阅读问题和答案的人就会变得混乱。请务必将新问题的链接发送给我,我会看看。【参考方案2】:

第一个类名应该是:LoadUserAsynTask

private fun getDataFromUrl() 
    val url = "https://pay-app-api.herokuapp.com/card/user/1"
    new LoadUserAsynTask(url).execute()



inner class LoadUserAsynTask: AsyncTask<String, String, String>() 
    private String url;
    LoadUserAsynTask(String url)
       this.url = url;
    


它应该是工作。这是文档:https://developer.android.com/reference/android/os/AsyncTask

【讨论】:

以上是关于Android AsyncTask 不运行的主要内容,如果未能解决你的问题,请参考以下文章

Android中的异步任务不使用AsyncTask

如何在 Android 中运行 AsyncTask?

Android - 强制取消 AsyncTask

Android SDK AsyncTask doInBackground未运行(子类)

Android -- 关闭AsyncTask(异步任务)

android:如果一个 AsyncTask 已经在运行,则阻止另一个 AsyncTask 执行