Android " tylko oryginalny wątek, który stworzył hierarchię widoków, może dotykać jego widoków."

Zbudowałem prosty odtwarzacz muzyczny w Androidzie. Widok dla każdego utworu zawiera SeekBar, zaimplementowany w następujący sposób:

public class Song extends Activity implements OnClickListener,Runnable {
    private SeekBar progress;
    private MediaPlayer mp;

    // ...

    private ServiceConnection onService = new ServiceConnection() {
          public void onServiceConnected(ComponentName className,
            IBinder rawBinder) {
              appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer
              progress.setVisibility(SeekBar.VISIBLE);
              progress.setProgress(0);
              mp = appService.getMP();
              appService.playSong(title);
              progress.setMax(mp.getDuration());
              new Thread(Song.this).start();
          }
          public void onServiceDisconnected(ComponentName classname) {
              appService = null;
          }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.song);

        // ...

        progress = (SeekBar) findViewById(R.id.progress);

        // ...
    }

    public void run() {
    int pos = 0;
    int total = mp.getDuration();
    while (mp != null && pos<total) {
        try {
            Thread.sleep(1000);
            pos = appService.getSongPosition();
        } catch (InterruptedException e) {
            return;
        } catch (Exception e) {
            return;
        }
        progress.setProgress(pos);
    }
}
To działa dobrze. Teraz chcę timer zliczający sekundy / minuty postępu utworu. Tak więc w layoucie umieszczam TextView, dostaję z findViewById() w onCreate(), i umieszczam to run() Po progress.setProgress(pos):
String time = String.format("%d:%d",
            TimeUnit.MILLISECONDS.toMinutes(pos),
            TimeUnit.MILLISECONDS.toSeconds(pos),
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(
                    pos))
            );
currentTime.setText(time);  // currentTime = (TextView) findViewById(R.id.current_time);

Ale ta ostatnia linijka daje mi wyjątek:

Android.widok.ViewRoot$CalledFromWrongThreadException: Only the oryginalny wątek, który utworzył hierarchię widoków, może dotknąć jego widoków.

Jednak robię to samo, co robię z SeekBar - tworząc widok w onCreate, a następnie dotykając go w run() - i to nie daje mi tej skargi.

Author: Cœur, 2011-03-02

30 answers

Musisz przenieść część zadania w tle, która aktualizuje interfejs użytkownika do głównego wątku. Jest do tego prosty fragment kodu:

runOnUiThread(new Runnable() {

    @Override
    public void run() {

        // Stuff that updates the UI

    }
});

Dokumentacja dla Activity.runOnUiThread.

Po prostu zagnieźdź to wewnątrz metody, która jest uruchomiona w tle, a następnie skopiuj wklej kod, który implementuje wszelkie aktualizacje w środku bloku. Dołącz tylko najmniejszą możliwą ilość kodu, w przeciwnym razie zaczniesz pokonywać cel wątku w tle.

 2036
Author: providence,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 00:59:09

Rozwiązałem to umieszczając runOnUiThread( new Runnable(){ .. wewnątrz run():

thread = new Thread(){
        @Override
        public void run() {
            try {
                synchronized (this) {
                    wait(5000);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dbloadingInfo.setVisibility(View.VISIBLE);
                            bar.setVisibility(View.INVISIBLE);
                            loadingText.setVisibility(View.INVISIBLE);
                        }
                    });

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Intent mainActivity = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(mainActivity);
        };
    };  
    thread.start();
 150
Author: Günay Gültekin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-17 13:12:18

Moje rozwiązanie:

private void setText(final TextView text,final String value){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            text.setText(value);
        }
    });
}

Wywołanie tej metody w wątku tła.

 77
Author: Angelo Angeles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:05:52

Zazwyczaj każda akcja z interfejsem użytkownika musi być wykonana w głównym lub UI wątku, czyli tym, w którym wykonywane są onCreate() i obsługa zdarzeń. Jednym ze sposobów na upewnienie się o tym jest użycie runOnUiThread(), innym jest użycie programów obsługi.

ProgressBar.setProgress() ma mechanizm, dla którego zawsze będzie uruchamiany na głównym wątku, dlatego zadziałał.

Zobacz Bezbolesne Gwintowanie .

 28
Author: bigstones,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-19 20:23:57

Byłem w tej sytuacji, ale znalazłem rozwiązanie z obiektem obsługi.

W moim przypadku, chcę zaktualizować Progresdialog z obserwator wzór . My view implementuje observer i nadpisuje metodę aktualizacji.

Więc mój główny wątek tworzy widok, a inny wątek wywołuje metodę update, która aktualizuje Progresdialop i....:

Tylko oryginalny wątek, który stworzył hierarchię widoków, może dotknąć jego widoki.

Możliwe jest Rozwiąż problem z obiektem obsługi.

Poniżej różne części mojego kodu:

public class ViewExecution extends Activity implements Observer{

    static final int PROGRESS_DIALOG = 0;
    ProgressDialog progressDialog;
    int currentNumber;

    public void onCreate(Bundle savedInstanceState) {

        currentNumber = 0;
        final Button launchPolicyButton =  ((Button) this.findViewById(R.id.launchButton));
        launchPolicyButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showDialog(PROGRESS_DIALOG);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case PROGRESS_DIALOG:
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setMessage("Loading");
            progressDialog.setCancelable(true);
            return progressDialog;
        default:
            return null;
        }
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch(id) {
        case PROGRESS_DIALOG:
            progressDialog.setProgress(0);
        }

    }

    // Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int current = msg.arg1;
            progressDialog.setProgress(current);
            if (current >= 100){
                removeDialog (PROGRESS_DIALOG);
            }
        }
    };

    // The method called by the observer (the second thread)
    @Override
    public void update(Observable obs, Object arg1) {

        Message msg = handler.obtainMessage();
        msg.arg1 = ++currentPluginNumber;
        handler.sendMessage(msg);
    }
}

To wyjaśnienie można znaleźć na tej stronie, i musisz przeczytać "przykładowy Progresdialog z drugim wątkiem".

 21
Author: Jonathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-29 16:07:31

Możesz użyć funkcji obsługi, aby usunąć Widok bez zakłócania głównego wątku interfejsu użytkownika. Oto przykładowy kod

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
          //do stuff like remove view etc
          adapter.remove(selecteditem);
          }
    });
 17
Author: Bilal Mustafa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-04 15:28:29

Kotlin koroutines może uczynić Twój kod bardziej zwięzłym i czytelnym w ten sposób:

MainScope().launch {
    withContext(Dispatchers.Default) {
        //TODO("Background processing...")
    }
    TODO("Update UI here!")
}

Lub odwrotnie:

GlobalScope.launch {
    //TODO("Background processing...")
    withContext(Dispatchers.Main) {
        // TODO("Update UI here!")
    }
    TODO("Continue background processing...")
}
 16
Author: KenIchi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-15 10:00:48

Widzę, że zaakceptowałeś odpowiedź @ providence. Na wszelki wypadek możesz również użyć obsługi! Najpierw wykonaj pola int.

    private static final int SHOW_LOG = 1;
    private static final int HIDE_LOG = 0;

Następnie utwórz instancję obsługi jako pole.

    //TODO __________[ Handler ]__________
    @SuppressLint("HandlerLeak")
    protected Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            // Put code here...

            // Set a switch statement to toggle it on or off.
            switch(msg.what)
            {
            case SHOW_LOG:
            {
                ads.setVisibility(View.VISIBLE);
                break;
            }
            case HIDE_LOG:
            {
                ads.setVisibility(View.GONE);
                break;
            }
            }
        }
    };

Stwórz metodę.

//TODO __________[ Callbacks ]__________
@Override
public void showHandler(boolean show)
{
    handler.sendEmptyMessage(show ? SHOW_LOG : HIDE_LOG);
}

Wreszcie, umieścić to w metodzie onCreate().

showHandler(true);
 8
Author: David Dimalanta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-20 06:55:42

Miałem podobny problem i moje rozwiązanie jest brzydkie, ale działa:

void showCode() {
    hideRegisterMessage(); // Hides view 
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            showRegisterMessage(); // Shows view
        }
    }, 3000); // After 3 seconds
}
 8
Author: Błażej,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:07:29

Użyj tego kodu i nie musisz runOnUiThread funkcji:

private Handler handler;
private Runnable handlerTask;

void StartTimer(){
    handler = new Handler();   
    handlerTask = new Runnable()
    {
        @Override 
        public void run() { 
            // do something  
            textView.setText("some text");
            handler.postDelayed(handlerTask, 1000);    
        }
    };
    handlerTask.run();
}
 7
Author: Hamid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-16 16:03:37

Używam Handler z Looper.getMainLooper(). Dla mnie zadziałało.

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
              // Any UI task, example
              textView.setText("your text");
        }
    };
    handler.sendEmptyMessage(1);
 7
Author: Sankar Behera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:08:47

Jest to jawne wywołanie błędu. Mówi, że każdy wątek stworzył Widok, tylko ten, który może dotknąć jego widoków. Dzieje się tak dlatego, że utworzony Widok znajduje się w przestrzeni tego wątku. Tworzenie widoku (GUI) odbywa się w głównym wątku interfejsu użytkownika. Tak więc zawsze używasz wątku interfejsu, aby uzyskać dostęp do tych metod.

Tutaj wpisz opis obrazka

Na powyższym obrazku zmienna progress znajduje się wewnątrz przestrzeni wątku interfejsu użytkownika. Tak więc tylko wątek interfejsu użytkownika może uzyskać dostęp do tej zmiennej. Tutaj masz dostęp do postępu poprzez new Thread () i dlatego masz błąd.

 7
Author: Uddhav Gautam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:10:18

Miałem do czynienia z podobnym problemem i żadna z wyżej wymienionych metod nie zadziałała dla mnie. W końcu to mi się udało:

Device.BeginInvokeOnMainThread(() =>
    {
        myMethod();
    });

Znalazłem ten klejnot tutaj .

 7
Author: Hagbard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-19 16:06:41

Stało się tak, gdy poprosiłem o zmianę interfejsu z doInBackground z Asynctask zamiast używać onPostExecute.

Radzenie sobie z UI w onPostExecute rozwiązało mój problem.

 6
Author: Jonathan dos Santos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:11:07

Pracowałam z klasą, która nie zawierała odniesienia do kontekstu. Więc nie było możliwe dla mnie, aby użyć runOnUIThread(); użyłem view.post(); i to zostało rozwiązane.

timer.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        final int currentPosition = mediaPlayer.getCurrentPosition();
        audioMessage.seekBar.setProgress(currentPosition / 1000);
        audioMessage.tvPlayDuration.post(new Runnable() {
            @Override
            public void run() {
                audioMessage.tvPlayDuration.setText(ChatDateTimeFormatter.getDuration(currentPosition));
            }
        });
    }
}, 0, 1000);
 4
Author: Ifta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:12:16

Przy użyciu AsyncTask zaktualizuj interfejs użytkownika w onpostexecute metodzie

    @Override
    protected void onPostExecute(String s) {
   // Update UI here

     }
 4
Author: Deepak Kataria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-10 13:30:03

Jeśli nie chcesz używać runOnUiThread API, możesz zaimplementować AsynTask dla operacji, które trwają kilka sekund. Ale w takim przypadku, również po przetworzeniu pracy w doinBackground(), musisz zwrócić gotowy widok w onPostExecute(). Implementacja systemu Android umożliwia interakcję z widokami tylko głównego wątku interfejsu użytkownika.

 3
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:06:48

Odpowiedź Kotlina

Musimy użyć wątku UI do zadania z true way. Możemy użyć wątku UI w Kotlinie:

runOnUiThread(Runnable {
   //TODO: Your job is here..!
})

@canerkaseler

 3
Author: canerkaseler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-04 16:13:18

To jest ślad stosu wspomnianego wyjątku

        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6149)
        at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:843)
        at android.view.View.requestLayout(View.java:16474)
        at android.view.View.requestLayout(View.java:16474)
        at android.view.View.requestLayout(View.java:16474)
        at android.view.View.requestLayout(View.java:16474)
        at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
        at android.view.View.requestLayout(View.java:16474)
        at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
        at android.view.View.setFlags(View.java:8938)
        at android.view.View.setVisibility(View.java:6066)

Więc jeśli pójdziesz i kopiesz to dowiesz się

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}

Gdzie mthread jest inicjalizacją w konstruktorze jak poniżej

mThread = Thread.currentThread();

Chodzi mi tylko o to, że kiedy tworzyliśmy konkretny widok, tworzyliśmy go w wątku UI, a później próbowaliśmy go modyfikować w wątku roboczym.

Możemy to zweryfikować za pomocą poniższego fragmentu kodu

Thread.currentThread().getName()

Kiedy nadmuchujemy layout, a później gdzie dostajesz wyjątek.

 2
Author: Amit Yadav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-19 09:06:12

Jeśli po prostu chcesz unieważnić (wywołać funkcję repaint/redraw) z wątku innego niż UI, użyj postInvalidate ()

myView.postInvalidate();

Spowoduje to opublikowanie żądania unieważnienia w wątku UI.

Aby uzyskać więcej informacji: what-does-postinvalidate-do

 2
Author: Nalin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-01 18:11:45

Dla mnie problemem było to, że dzwoniłem onProgressUpdate() wprost z mojego kodu. To nie powinno być zrobione. Zadzwoniłem publishProgress() zamiast tego i to rozwiązało błąd.

 1
Author: mindreader,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-04 08:23:13

W moim przypadku, Mam EditText w adapterze i jest już w wątku UI. Jednak gdy ta aktywność się ładuje, ulega awarii z tym błędem.

Moim rozwiązaniem jest to, że muszę usunąć <requestFocus /> z EditText w XML.

 1
Author: Sruit A.Suk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-22 01:08:16

Dla osób zmagających się w Kotlinie działa to tak:

lateinit var runnable: Runnable //global variable

 runOnUiThread { //Lambda
            runnable = Runnable {

                //do something here

                runDelayedHandler(5000)
            }
        }

        runnable.run()

 //you need to keep the handler outside the runnable body to work in kotlin
 fun runDelayedHandler(timeToWait: Long) {

        //Keep it running
        val handler = Handler()
        handler.postDelayed(runnable, timeToWait)
    }
 1
Author: Tarun Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-02 08:05:03

Jeśli znajdujesz się w fragmencie, musisz również uzyskać obiekt activity, ponieważ runOnUIThread jest metodą na aktywności.

Przykład w Kotlinie z jakimś otaczającym kontekstem, aby był jaśniejszy - ten przykład nawiguje od fragmentu kamery do fragmentu galerii:

// Setup image capture listener which is triggered after photo has been taken
imageCapture.takePicture(
       outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback {

           override fun onError(exc: ImageCaptureException) {
           Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
        }

        override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                        val savedUri = output.savedUri ?: Uri.fromFile(photoFile)
                        Log.d(TAG, "Photo capture succeeded: $savedUri")
               
             //Do whatever work you do when image is saved         
             
             //Now ask navigator to move to new tab - as this
             //updates UI do on the UI thread           
             activity?.runOnUiThread( {
                 Navigation.findNavController(
                        requireActivity(), R.id.fragment_container
                 ).navigate(CameraFragmentDirections
                        .actionCameraToGallery(outputDirectory.absolutePath))
              })
 1
Author: Mick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-22 20:24:43

Możesz to zrobić w ten sposób.

Https://developer.android.com/reference/android/view/View#post (java. lang. Runnable)

Proste podejście

currentTime.post(new Runnable(){
            @Override
            public void run() {
                 currentTime.setText(time);     
            }
        }

Zapewnia również opóźnienie

Https://developer.android.com/reference/android/view/View#postDelayed(java.lang.Runnable,%20long)

 1
Author: rahat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-28 17:29:59

Rozwiązany: po prostu umieść tę metodę w klasie doInBackround... and pass the message

public void setProgressText(final String progressText){
        Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                // Any UI task, example
                progressDialog.setMessage(progressText);
            }
        };
        handler.sendEmptyMessage(1);

    }
 0
Author: Kaushal Sachan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-28 08:06:01

W moim przypadku, wywołanie zbyt wiele razy w krótkim czasie spowoduje ten błąd, po prostu umieścić czas, który upłynął sprawdzanie nic nie zrobić, jeśli zbyt krótki, np. zignorować, jeśli funkcja zostanie wywołana mniej niż 0.5 sekundy: {]}

    private long mLastClickTime = 0;

    public boolean foo() {
        if ( (SystemClock.elapsedRealtime() - mLastClickTime) < 500) {
            return false;
        }
        mLastClickTime = SystemClock.elapsedRealtime();

        //... do ui update
    }
 0
Author: Fruit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-11 08:03:14

Jeśli nie możesz znaleźć UIThread, możesz użyć tego sposobu .

Yourcurrentcontext oznacza, że musisz przeanalizować bieżący kontekst

 new Thread(new Runnable() {
        public void run() {
            while (true) {
                (Activity) yourcurrentcontext).runOnUiThread(new Runnable() {
                    public void run() { 
                        Log.d("Thread Log","I am from UI Thread");
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (Exception ex) {

                }
            }
        }
    }).start();
 0
Author: Udara Kasun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-02 05:41:25

W Kotlin po prostu umieść swój kod w metodzie runonuithread activity

runOnUiThread{
    // write your code here, for example
    val task = Runnable {
            Handler().postDelayed({
                var smzHtcList = mDb?.smzHtcReferralDao()?.getAll()
                tv_showSmzHtcList.text = smzHtcList.toString()
            }, 10)

        }
    mDbWorkerThread.postTask(task)
}
 0
Author: Raheel Khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-04 19:16:42

RunOnUIThread nie wydaje się działać dla mnie, ale następujące skończyło się rozwiązaniem moich problemów.

            _ = MainThread.InvokeOnMainThreadAsync(async () =>
           {
               this.LoadApplication(Startup.Init(this.ConfigureServices));

               var authenticationService = App.ServiceProvider.GetService<AuthenticationService>();
               if (authenticationService.AuthenticationResult == null)
               {
                   await authenticationService.AuthenticateAsync(AuthenticationUserFlow.SignUpSignIn, CrossCurrentActivity.Current.Activity).ConfigureAwait(false);
               }
           });

W trakcie uruchamiania.Metoda Init jest reactiveui routing i to musi być wywołane w głównym wątku. Ta metoda wywoływania akceptuje również asynchroniczne/oczekujące lepsze niż RunOnUIThread.

Więc gdziekolwiek muszę wywoływać metody na mainthreadzie używam tego.

Proszę o komentarz, jeśli ktoś wie coś, czego Nie wiem I może pomóc mi poprawić moją aplikację.

 0
Author: Justin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-23 19:49:12