【发布时间】:2016-11-08 08:26:23
【问题描述】:
我根据亲爱的 Mayank'answer 编辑了我的代码,但它没有显示在方法开始之前在 displayMsg() 方法中作为输入发送的任何消息。我应该说 MethodTest() 是使用 nfc 和方法 onNewIntent(Intent意图)
@Override
protected void onNewIntent(Intent intent) {
MethodTest();
..............
}
public void MethodTest() {
DisplayMsg("method 1 is running");
Method1();
DisplayMsg("method 2 is running");
Method2();
DisplayMsg("method 3 is running");
Method3();
}
private int DisplayMsg(String msg) {
totalMsg += msg;
DisplayMsgClass dc = new DisplayMsgClass();
dc.doInBackground(totalMsg);
}
private class DisplayMsgClass extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
textView.setText("Hello !!!");
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... Messages) {
return Messages[0];
}
@Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.INVISIBLE);
textView.setText(result);
}
}
在我的布局中:
<LinearLayout>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:id="@+id/progressBar1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textv1"
android:hint="AppletPass"
android:gravity="center"/>
</LinearLayout>
【问题讨论】:
-
int value= obj.doInBackground(msg);是什么意思?请参阅AsyncTask 了解正确的 AsyncTask 实现 -
这并不重要。我把它放在确保 DisplayMsg 被执行并创建一个可以看到对话框的时间
-
好的,使用
obj.execute("");代替int value= obj.doInBackground(msg);并检查ProgressDialog是否显示 -
如果你想等到异步任务执行,在调用异步任务时添加.get,但不推荐,因为UI会冻结直到得到结果
-
obj.execute("") 不工作。我在“onProgressUpdate”上设置了断点,但我看到 Method1() 何时完成,onProgressUpdate 被调用。为什么?