我在AsyncTask期間嘗試顯示和隱藏對話框時遇到了問題我已將放在一起的活動放在我的Android應用程序中。AysncTask - 從主UI調用線程
這是目前我在做什麼:
public void syncCard(final Tag tag) {
syncTask = new SyncTask();
syncTask.execute(tag);
}
private class SyncTask extends AsyncTask<Tag, Void, Void> {
private final Dialog dialog;
private boolean mException;
public SyncTask() {
// Prepare dialog
dialog = buildSyncingDialog();
}
@Override
protected void onPreExecute() {
dialog.show();
}
@Override
protected Void doInBackground(Tag... params) {
mTagcomm = IsoDep.get(params[0]);
if (mTagcomm == null) {
//TODO - Handle communication error with the present card
}
mException = false;
try {
// Open connection
mTagcomm.connect();
lastAts = getAts(mTagcomm);
mProvider.setmTagCom(mTagcomm);
EmvParser parser = new EmvParser(mProvider, true);
mCard = parser.readEmvCard();
if (mCard != null) {
mCard.setAtrDescription(extractAtsDescription(lastAts));
}
} catch (IOException e) {
mException = true;
} finally {
// close tagcomm
IOUtils.closeQuietly(mTagcomm);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (!mException) {
if (mCard != null) {
showPaymentCardDetails();
} else if (mCard.isNfcLocked()) {
//TODO - Show error message informing user the card is locked
}
} else {
}
}
private Dialog buildSyncingDialog() {
String syncingText = String.format("%s\n%s",
getString(R.string.syncing), getString(R.string.do_not_remove_card));
Dialog dialog = new CustomDialog(PaymentCardRegisterActivity.this,
syncingText, R.layout.layout_syncing);
dialog.setCancelable(false);
return dialog;
}
@Override
public void onCancelled() {
dialog.dismiss();
}
}
我看到了以下錯誤:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我碰到這個老答案出來 - Can't create handler inside thread which has not called Looper.prepare()
但我對於我需要做什麼,m仍然有點困惑,對這篇文章的最後一個迴應是說從UI線程運行任務,我將如何使用上面的代碼去做這件事?
編輯
我的活動課,因爲我使用這個類來讀取非接觸式卡的詳細信息延伸NfcActivity
。
我syncCard
正在從另一個後臺線程(我相信)被稱爲像這樣
@Override
public void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
processIntent(intent);
}
private void processIntent(final Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
onTagDiscovered(tagFromIntent);
}
}
@Override
public void onTagDiscovered(final Tag tag) {
super.onTagDiscovered(tag);
try {
PaymentCardRegisterActivity.this.syncCard(tag);
} catch (Exception e) {
Log.e(PaymentCardRegisterActivity.class.getName(), "Failed to sync card", e);
// Return to start activity
finish();
}
}
如何/哪裏是'syncCard()'叫什麼名字? – codeMagic
你可能會從一些後臺線程開始asynctask –
啊,好吧,我確實從後臺線程開始。我正確地認爲主UI線程來自Activity類中'onCreate'中的調用? – mindparse