Search code examples
androidandroid-asynctaskhttprequestnfc

Pass a string to ASyncTask when NDEF_DISCOVERED


I am working in NFC tag. My task is that when a NFC is scanned, I must read the NFC information and send it to ASyncTask. In ASyncTask, I will used the HttpClient to send that information to server. I read NFC information successfully. I searched and found my solution. I just used the simplest solution such as below. That code works well. The ASyncTask is initialized in ACTION_NDEF_DISCOVERED, hence, when tag is scanned, ASyncTask will be created and call the request to server. My problem is that ASyncTask created many times (whenever tag is scanned). Do we have any way to create ASyncTask just one time in onCreate, and we will pass a string to the ASyncTask when tag is scan?

    /////Read NFC Information///////////////
    @Override
    protected void onNewIntent(Intent intent) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            //Read NFC tag succesfull
            String NFC_information=100;
            new AsyncCallWS().execute("101");            
        }
    }
    private class AsyncCallWS extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... params) {
            String url="server_link"+params[0];
            try {               
                String content_feedback=getStringContent(url);

            } catch (Exception e) {e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
        }
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }
        @Override
        protected void onProgressUpdate(Void... values) {
            Log.i(TAG, "onProgressUpdate");
        }
    }
    public static String getStringContent(String uri) throws Exception {
    {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(uri));
            HttpResponse response = client.execute(request);
            InputStream ips  = response.getEntity().getContent();
            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
            StringBuilder sb = new StringBuilder();
            String s;
            while(true )
            {
                s = buf.readLine();
                if(s==null || s.length()==0)
                    break;
                sb.append(s);

            }
            buf.close();
            ips.close();
            return sb.toString();

            } 
        finally { }
    }

Solution

  • You can do it like below:

    public void onResume() {
        super.onResume();
        ...
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                    //consider single message is there hence loop will iterate only once
                    new MyAsync().execute(msgs[i]);
                }
            }
        }
        //process the msgs array
    }
    
    <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="text/plain" />
    </intent-filter>
    

    Because after calling onNewIntent, onResume gets called.