我编写了以下代码,以更好地理解Handler和Looper。我很想知道在特定情况下如何退出Looper 例如,当计数器达到特定限制时。
在下面的代码中,我想在“ what”等于10时在线程T的循环程序上调用.quit()。 根据我在下面编写的代码,即使“ what”的内容超过10,“ handleMessage”方法也将被调用...我希望在.quit()时 被调用后,“ handleMessage”将不再被调用。
请让我知道如何正确退出Looper。
app.gradle
public class ActMain extends AppCompatActivity {
private static final String TAG = ActMain.class.getSimpleName();
private Handler mHandler = null;
private Button mBtnValues = null;
private int i = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_act_main);
this.mBtnValues = findViewById(R.id.btnValues);
this.mBtnValues.setOnClickListener(x-> {
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("what", "" + i++);
Log.d(TAG, "i: " + i);
msg.setData(bundle);
mHandler.sendMessage(msg);
});
new T().start();
}
private class T extends Thread {
private String str = "";
public T() {}
@Override
public void run() {
super.run();
Log.d(TAG, "run method started");
Looper.prepare();
Log.d(TAG, "beginning of the looped section");
final String[] cnt = {""};
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String what= msg.getData().getString("what");
str += what;
Log.d(TAG, "new str: " + str);
}
};
Log.d(TAG, "end of the looped section");
if (i == 10) {
Looper.myLooper().quit();
}
Looper.loop();
}
}
}