AsyncTask застрял - PullRequest
       31

AsyncTask застрял

0 голосов
/ 15 марта 2019

Я получил AsyncTask, который должен читать информацию с URL на Стрин.

MainActivity:

  package e.marco.myapplication;


import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;


import java.util.Arrays;

import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {
    public String check;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new statistik().execute();
    }
    public class statistik extends AsyncTask<String, Void, String[]> {

        @Override

        protected String[] doInBackground(String... strings) {
            Log.d("test", "test1");

            check = "";

            try {
                check = new URLconnection("www.myurl.com").execute().get();

            } catch (ExecutionException e) {
                e.printStackTrace();
                ;
            } catch (InterruptedException e) {
                e.printStackTrace();

            }


            Log.d("test", "test2");
            Log.d("test", check);
            String statistik[] = check.split("\n",-1);
            Log.d("test", Arrays.toString(statistik));

            return  statistik;
        }
    }
    }

Если я запускаю свой проект в Logcat, я вижу только вывод Log.d ("teset", "test1") и больше ничего. Я думаю, что это застряло в попытке ... URLconnection класс работает, поэтому с этим проблем нет Если я помещу этот код из AsyncTask и напишу его в классе onCreate, он будет работать нормально. Так почему же он застрял в AsyncTask, а в классе onCreate нет?

Редактировать: я вызываю задачу в классе onCreate следующим образом:

 new statistik().execute();

Класс Urlconnection:

public class URLconnection extends AsyncTask<String, Void, String> {
    String urlll;

    public URLconnection(String urltext) {
        super();

        urlll = urltext;


    }

    private String readStream(InputStream is) {
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            int i = is.read();
            while (i != -1) {
                bo.write(i);
                i = is.read();
            }
            return bo.toString();
        } catch (IOException e) {
            return "";
        }
    }

    @Override
    protected String doInBackground(String... strings) {

        String test = "Error";
        URL url = null;


        try {
            url = new URL(urlll);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                test = readStream(in);
            } finally {
                urlConnection.disconnect();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return test;


    }


}

Logcat под Android 9 / API 28 Отладка:

2019-03-15 10:06:12.794 20358-20358/? I/arco.swimcommi: Not late-enabling -Xcheck:jni (already on)
2019-03-15 10:06:12.814 20358-20358/? W/arco.swimcommi: Unexpected CPU variant for X86 using defaults: x86
2019-03-15 10:06:12.928 20358-20358/e.marco.swimcommit W/ActivityThread: Application e.marco.swimcommit is waiting for the debugger on port 8100...
2019-03-15 10:06:12.929 20358-20358/e.marco.swimcommit I/System.out: Sending WAIT chunk
2019-03-15 10:06:13.932 20358-20358/e.marco.swimcommit I/System.out: Debugger has connected
2019-03-15 10:06:13.932 20358-20358/e.marco.swimcommit I/System.out: waiting for debugger to settle...
2019-03-15 10:06:14.133 20358-20358/e.marco.swimcommit I/chatty: uid=10090(e.marco.swimcommit) identical 1 line
2019-03-15 10:06:14.334 20358-20358/e.marco.swimcommit I/System.out: waiting for debugger to settle...
2019-03-15 10:06:14.535 20358-20358/e.marco.swimcommit I/System.out: waiting for debugger to settle...
2019-03-15 10:06:14.939 20358-20358/e.marco.swimcommit I/chatty: uid=10090(e.marco.swimcommit) identical 2 lines
2019-03-15 10:06:15.140 20358-20358/e.marco.swimcommit I/System.out: waiting for debugger to settle...
2019-03-15 10:06:15.342 20358-20358/e.marco.swimcommit I/System.out: debugger has settled (1472)
2019-03-15 10:06:15.595 20358-20358/e.marco.swimcommit W/arco.swimcommi: JIT profile information will not be recorded: profile file does not exits.
2019-03-15 10:06:15.607 20358-20358/e.marco.swimcommit I/chatty: uid=10090(e.marco.swimcommit) identical 10 lines
2019-03-15 10:06:15.608 20358-20358/e.marco.swimcommit W/arco.swimcommi: JIT profile information will not be recorded: profile file does not exits.
2019-03-15 10:06:15.632 20358-20358/e.marco.swimcommit I/InstantRun: starting instant run server: is main process
2019-03-15 10:06:15.859 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
2019-03-15 10:06:15.859 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
2019-03-15 10:06:16.234 20358-20388/e.marco.swimcommit D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2019-03-15 10:06:16.477 20358-20358/e.marco.swimcommit D/OpenGLRenderer: Skia GL Pipeline
2019-03-15 10:06:16.662 20358-20393/e.marco.swimcommit I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2019-03-15 10:06:16.662 20358-20393/e.marco.swimcommit I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
2019-03-15 10:06:16.662 20358-20393/e.marco.swimcommit I/OpenGLRenderer: Initialized EGL, version 1.4
2019-03-15 10:06:16.662 20358-20393/e.marco.swimcommit D/OpenGLRenderer: Swap behavior 1
2019-03-15 10:06:16.663 20358-20393/e.marco.swimcommit W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2019-03-15 10:06:16.663 20358-20393/e.marco.swimcommit D/OpenGLRenderer: Swap behavior 0
2019-03-15 10:06:16.675 20358-20393/e.marco.swimcommit D/EGL_emulation: eglCreateContext: 0xedac0d40: maj 3 min 0 rcv 3
2019-03-15 10:06:16.701 20358-20393/e.marco.swimcommit D/EGL_emulation: eglMakeCurrent: 0xedac0d40: ver 3 0 (tinfo 0xe63d00d0)
2019-03-15 10:06:16.780 20358-20358/e.marco.swimcommit W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@df988d6
2019-03-15 10:06:16.880 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/graphics/FontFamily;-><init>()V (light greylist, reflection)
2019-03-15 10:06:16.880 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/graphics/FontFamily;->addFontFromAssetManager(Landroid/content/res/AssetManager;Ljava/lang/String;IZIII[Landroid/graphics/fonts/FontVariationAxis;)Z (light greylist, reflection)
2019-03-15 10:06:16.880 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/graphics/FontFamily;->addFontFromBuffer(Ljava/nio/ByteBuffer;I[Landroid/graphics/fonts/FontVariationAxis;II)Z (light greylist, reflection)
2019-03-15 10:06:16.880 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/graphics/FontFamily;->freeze()Z (light greylist, reflection)
2019-03-15 10:06:16.880 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/graphics/FontFamily;->abortCreation()V (light greylist, reflection)
2019-03-15 10:06:16.880 20358-20358/e.marco.swimcommit W/arco.swimcommi: Accessing hidden method Landroid/graphics/Typeface;->createFromFamiliesWithDefault([Landroid/graphics/FontFamily;Ljava/lang/String;II)Landroid/graphics/Typeface; (light greylist, reflection)
2019-03-15 10:06:17.163 20358-20358/e.marco.swimcommit I/Choreographer: Skipped 35 frames!  The application may be doing too much work on its main thread.
2019-03-15 10:06:17.206 20358-20393/e.marco.swimcommit D/EGL_emulation: eglMakeCurrent: 0xedac0d40: ver 3 0 (tinfo 0xe63d00d0)
2019-03-15 10:06:17.468 20358-20393/e.marco.swimcommit D/EGL_emulation: eglMakeCurrent: 0xedac0d40: ver 3 0 (tinfo 0xe63d00d0)
2019-03-15 10:06:17.545 20358-20393/e.marco.swimcommit D/EGL_emulation: eglMakeCurrent: 0xedac0d40: ver 3 0 (tinfo 0xe63d00d0)
2019-03-15 10:06:17.649 20358-20393/e.marco.swimcommit D/EGL_emulation: eglMakeCurrent: 0xedac0d40: ver 3 0 (tinfo 0xe63d00d0)
2019-03-15 10:06:17.708 20358-20393/e.marco.swimcommit I/chatty: uid=10090(e.marco.swimcommit) RenderThread identical 1 line
2019-03-15 10:06:17.769 20358-20393/e.marco.swimcommit D/EGL_emulation: eglMakeCurrent: 0xedac0d40: ver 3 0 (tinfo 0xe63d00d0)
2019-03-15 10:06:18.774 20358-20393/e.marco.swimcommit D/EGL_emulation: eglMakeCurrent: 0xedac0d40: ver 3 0 (tinfo 0xe63d00d0)
2019-03-15 10:06:20.307 20358-20396/e.marco.swimcommit D/test: test1

1 Ответ

1 голос
/ 15 марта 2019

Согласно документации , вы должны запустить AsyncTask в потоке пользовательского интерфейса.Если вы хотите попробовать запустить вторую задачу внутри первой, вы можете сделать это следующим образом:

mainActivity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        ...
        check = new URLconnection("www.myurl.com").execute().get();
        ...
    }
}

Это не чистый способ.Я предлагаю переписать ваш код и добавить все методы блокировки внутри первой задачи.

...