首页 > 解决方案 > 片段中的线程只调用一次

问题描述

我正在尝试实现一个线程,该线程在Fragment. 因此我需要参考主线程。根据我的研究,我发现以下代码应该可以解决问题:

new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(menuActivity, "HELLO", Toast.LENGTH_SHORT).show();
        }
    });

这只会执行一次,即使Looper通常应该保持线程处于活动状态。尝试在Looper.prepare()内部调用Handler将导致 a因为每个线程 RuntimeException只允许一个。编辑:我的目标是每秒永久更新一个 TextView。Looper

我还尝试了以下方法:

Thread t = new Thread() {
        @Override
        public void run() {
            menuActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("-----------TEST");
                }

            }); 
        }
    };
t.start();

但这也只会执行一次。

我也读过这篇文章,但我想我的第一个代码片段只是文章中显示的代码的较短版本。

在这些代码片段中,我的错误可能在哪里?

这个问题不是重复的,因为我提出了一个完全不同的代码片段,这是我遇到的问题的基础。此外,Looper 在此线程中进行了更深入的解释。

标签: androidmultithreadingui-thread

解决方案


我了解到您想在 1 秒后重复更新文本视图。这是我刚刚写的一个简单的演示。

样机屏幕

在此处输入图像描述

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text_view_money"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="startUpdateTextViewMoney"
            android:text="Start" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="stopUpdateTextViewMoney"
            android:text="Stop" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edit_text_money"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="setMoney"
            android:text="SET MONEY" />

    </LinearLayout>

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private static final int UPDATE_TEXT_MONEY_INTERVAL = 1000;

    private Handler mMainHandler;

    private TextView mTextViewMoney;
    private TextView mEditTextMoney;

    private String money;

    private Runnable mUpdateTextViewMoneyTask = new Runnable() {
        @Override
        public void run() {
            if (TextUtils.isEmpty(money)) {
                mTextViewMoney.setText(String.valueOf(SystemClock.elapsedRealtime()));
            } else {
                mTextViewMoney.setText(money);
                money = null;
            }
            mMainHandler.postDelayed(this, UPDATE_TEXT_MONEY_INTERVAL);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextViewMoney = findViewById(R.id.text_view_money);
        mEditTextMoney = findViewById(R.id.edit_text_money);

        mMainHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopUpdateTextViewMoney(null);
    }

    public void startUpdateTextViewMoney(View view) {
        mMainHandler.post(mUpdateTextViewMoneyTask);
    }

    public void stopUpdateTextViewMoney(View view) {
        mMainHandler.removeCallbacks(mUpdateTextViewMoneyTask);
    }

    public void setMoney(View view) {
        String money = mEditTextMoney.getText().toString();
        this.money = !TextUtils.isEmpty(money) ? money : "";
    }
}
  • 当用户按下开始按钮时,应用程序将开始每秒更新文本视图
  • 当用户按下停止按钮时,应用程序将停止更新文本视图。
  • 如果用户想设置下次显示的新货币,只需在编辑文本中输入,然后按设置货币。

推荐阅读