Android AsyncTask无法运行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android AsyncTask无法运行相关的知识,希望对你有一定的参考价值。

我在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
答案

你的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是安全的。

另一答案

第一个类名应为: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;
    }

}

这应该是有效的。这是doc:https://developer.android.com/reference/android/os/AsyncTask

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

Android SQLite 更新无法在 AsyncTask 的后台运行

Android AsyncTask无法运行

Asynctask 崩溃 ViewPager RecyclerView (Android)

从片段调用 Android AsyncTask 没有调用其成员 - doInbackground、onpreexecute、onpostexecute

Android AsyncTask 与特定情况下的线程

android中AsyncTask中的ProgressDialog