Android Studio 为什么我的线程会中断整个Android应用程序?

z9gpfhce  于 2023-08-07  发布在  Android
关注(0)|答案(2)|浏览(168)

我正尝试在用户处于主活动时使TextView Flink 。
我创建了一个新的线程,但发生的是,TextView的可见性打开,而不是关闭,然后应用程序关闭与Android说,应用程序停止工作本身。
看起来像是for循环执行了一个,然后整个应用程序被中断了。
下面是一段代码

  1. Thread blinkThread = new Thread(){
  2. @Override
  3. public void run() {
  4. for(int i = 0; i < 10; i++){
  5. lastletter.setVisibility(VISIBLE);
  6. try {
  7. sleep(500);
  8. } catch (InterruptedException e) {
  9. throw new RuntimeException(e);
  10. }
  11. lastletter.setVisibility(View.INVISIBLE);
  12. try {
  13. sleep(500);
  14. } catch (InterruptedException e) {
  15. throw new RuntimeException(e);
  16. }
  17. }
  18. }
  19. };

字符串
上面的代码位于MainActivity类中。线程在onCreate()方法中启动,我基本上写了blinkThread.start()

q7solyqu

q7solyqu1#

在android中,从主线程以外的其他线程操作视图会引发异常。
您需要为主线程创建一个处理程序。

  1. private final Handler mainHandler = new Handler(getMainLooper());

字符串
并将runnables发送到它。

  1. Thread blinkThread = new Thread() {
  2. @Override
  3. public void run() {
  4. for (int i = 0; i < 10; i++) {
  5. // the main thread will handle this
  6. mainHandler.post(() -> lastletter.setVisibility(View.VISIBLE));
  7. try {
  8. sleep(500);
  9. } catch (InterruptedException e) {
  10. throw new RuntimeException(e);
  11. }
  12. mainHandler.post(() -> lastletter.setVisibility(View.INVISIBLE));
  13. try {
  14. sleep(500);
  15. } catch (InterruptedException e) {
  16. throw new RuntimeException(e);
  17. }
  18. }
  19. }
  20. };

展开查看全部
hmtdttj4

hmtdttj42#

在这里,我创建了一个名为blinkCall()的方法,它有Handler(),我定义了1秒 Flink textview
尝试使用下面的代码:
代码:

  1. private void blinkCall() {
  2. final Handler handler = new Handler();
  3. new Thread(new Runnable() {
  4. @Override
  5. public void run() {
  6. int timeToBlink = 1000;
  7. try {
  8. Thread.sleep(timeToBlink);
  9. } catch (Exception e) {
  10. }
  11. handler.post(new Runnable() {
  12. @Override
  13. public void run() {
  14. if (textView.getText().toString().equals("")) {
  15. textView.setText("Abhishek");
  16. } else {
  17. textView.setText("");
  18. }
  19. blinkCall();
  20. }
  21. });
  22. }
  23. }).start();
  24. }

字符串

展开查看全部

相关问题