简体   繁体   中英

Android: Making application wait before executing task (AsyncTask usage)

Hello I will define my problem more clearly here. I am working on my first Android App that reads simply an NFC Tag and compares it to an SQLite database stored on the device.

In short, if this is successful (Tag is ok, code exists in the database) the screen changes to reflect it. If it fails (tag not ok, tag code does not exist in the database) it again changes to show this. What I am trying to accomplish is to make the screen return to its initial state after say 2 seconds when the either OK or error views are displayed.

I have tried several options but I was unable to do so hence why I am asking. Thread.sleep() does not seem to do it. I tried executing it after verifying if the Asynctask's status is finished but not to much luck either. Code below:

// 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);
                }
            }
        }
    }
}

This is my AsyncTask class, i will post more code if needed but this is what i've been doing so far.

I also tried the code below in onPostExecute as well but the screen did not even change anymore to either error or success.

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);
}

When you have to do tasks based on time in Android you should use a Handler .

In your case use Handler.postDelayed(Runnable, long) . Create and execute the handler in your onPostExecute .

The problem with your approach

By using Thread.sleep you stopped the execution of the current thread, which in onPostExecute is the UI Thread hence you couldn't see it getting updated in either success or failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM