Android:在执行任务之前使应用程序等待(AsyncTask用法)

时间:2015-06-12 08:44:40

标签: java android multithreading sqlite android-asynctask

您好我会在这里更清楚地定义我的问题。我正在开发我的第一个只读NFC标签的Android应用程序,并将其与存储在设备上的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);
}

1 个答案:

答案 0 :(得分:2)

如果您必须在Android中根据时间执行任务,则应使用Handler

在您的情况下使用Handler.postDelayed(Runnable, long)。在onPostExecute

中创建并执行处理程序

您的方法存在的问题

通过使用Thread.sleep,您停止了当前线程的执行,onPostExecute中的UI Thread <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="#CABBBBBB"/> <corners android:radius="2dp" /> </shape> </item> <item android:left="0dp" android:right="1dp" android:top="0dp" android:bottom="2dp"> <shape android:shape="rectangle"> <solid android:color="@android:color/white"/> <corners android:radius="1dp" /> </shape> </item> </layer-list> ,因此您无法在成功或失败时看到它更新。