【问题标题】:Android: Making application wait before executing task (AsyncTask usage)Android:在执行任务之前让应用程序等待(AsyncTask 用法)
【发布时间】:2015-08-28 05:15:25
【问题描述】:

您好,我将在这里更清楚地定义我的问题。我正在开发我的第一个 Android 应用程序,它只读取一个 NFC 标签并将其与存储在设备上的 SQLite 数据库进行比较。

简而言之,如果这是成功的(标签没问题,代码存在于数据库中)屏幕会改变以反映它。如果失败(标记不正确,数据库中不存在标记代码),它会再次更改以显示此内容。我想要完成的是在显示 OK 或错误视图时让屏幕在 2 秒后返回其初始状态。

我已经尝试了几个选项,但我无法这样做,因此我问了这个问题。 Thread.sleep() 似乎没有这样做。在验证 Asynctask 的状态是否已完成后,我尝试执行它,但也不是很幸运。代码如下:

// Internal Class used to define NdefReaderTask
private class NdefReaderTask extends AsyncTask<Tag, Void, String> {

    @Override
    protected String doInBackground(Tag... params) {
        Tag tag = params[0];

        Ndef ndef = Ndef.get(tag);
        if (ndef == null) {
            return null;
        }

        NdefMessage ndefMessage = ndef.getCachedNdefMessage();

        NdefRecord[] records = ndefMessage.getRecords();

        for (NdefRecord ndefRecord : records) {
            if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN
                    && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                try {
                    return readText(ndefRecord);
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "Unsupported encoding", e);
                }
            }
        }

        return null;
    }

    private String readText(NdefRecord record)
            throws UnsupportedEncodingException {
        byte[] payload = record.getPayload();

        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
        int languageCodeLength = payload[0] & 0063;

        return new String(payload, languageCodeLength + 1, payload.length
                - languageCodeLength - 1, textEncoding);
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            // Do SOMETHING HERE
            // find the tag which has the same code as result
            EventTag currentTag = dataSource.getEventTag(result);
            if (currentTag != null) {
                Toast.makeText(
                        getApplicationContext(),
                        "Welcome " + currentTag.getFullName()
                        + " you are using tag: "
                        + currentTag.getNfcCode(), Toast.LENGTH_LONG)
                        .show();
                ((TextView) findViewById(R.id.fullscreen_content))
                .setBackgroundResource(R.drawable.bggreen);
                ((TextView) findViewById(R.id.fullscreen_content))
                .setText(getResources().getString(R.string.txt_tag_ok)
                        + " " + currentTag.getFullName());

            } else {
                Toast.makeText(getApplicationContext(),
                        "Tag with code: " + result + " not found in database",
                        Toast.LENGTH_LONG).show();
                ((TextView) findViewById(R.id.fullscreen_content))
                .setBackgroundResource(R.drawable.bgred);
                ((TextView) findViewById(R.id.fullscreen_content))
                .setText(getResources().getString(
                        R.string.txt_tag_notok));

            }

            if (this.getStatus() == Status.FINISHED) {
                try {
                    Thread.sleep(miliseconds);
                    ((TextView) findViewById(R.id.fullscreen_content))
                    .setBackgroundResource(R.drawable.bgblue);
                    ((TextView) findViewById(R.id.fullscreen_content))
                    .setText(getResources().getString(
                            R.string.dummy_content));
                } catch (Exception exp) {
                    Log.d("Thread Error", "Unable to sleep thread for "
                            + miliseconds, exp);
                }
            }
        }
    }
}

这是我的 AsyncTask 类,如果需要,我会发布更多代码,但这是我迄今为止所做的。

我也在 onPostExecute 中尝试了下面的代码,但屏幕甚至不再变为错误或成功。

try {
    this.get(miliseconds, TimeUnit.MILLISECONDS);
    ((TextView) findViewById(R.id.fullscreen_content)).setBackgroundResource(
            R.drawable.bgblue);
    ((TextView) findViewById(R.id.fullscreen_content)).setText(
            getResources().getString(R.string.dummy_content));
}
catch(Exception exp) {
    Log.d("Thread Error", "Unable to sleep thread for " + miliseconds, exp);
}

【问题讨论】:

标签: java android multithreading sqlite android-asynctask


【解决方案1】:

当您必须在 Android 中根据时间执行任务时,您应该使用 Handler

在您的情况下使用Handler.postDelayed(Runnable, long)。在onPostExecute 中创建并执行处理程序。

您的方法存在问题

通过使用Thread.sleep,您停止了当前线程的执行,在onPostExecute 中是UI Thread,因此无论成功还是失败,您都看不到它的更新。

【讨论】:

  • 谢谢,就是这样。我将不得不阅读有关处理程序的更多信息!
猜你喜欢
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
相关资源
最近更新 更多