我正在使用NFC标签。我的任务是扫描NFC时,我必须阅读NFC信息并将其发送到ASyncTask
。在ASyncTask
中,我将使用HttpClient
将该信息发送到服务器。我成功读取了NFC信息。我搜索并找到了我的解决方案。我刚刚使用了最简单的解决方案,如下所示。该代码运作良好。 ASyncTask
初始化ACTION_NDEF_DISCOVERED
,因此,在扫描标记时,将创建ASyncTask
并将请求调用到服务器。我的问题是ASyncTask
创建了很多次(每当扫描标签时)。我们是否有办法在ASyncTask
中一次创建onCreate
,我们会在标记扫描时将字符串传递给ASyncTask
?
/////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 { }
}
答案 0 :(得分:1)
你可以这样做:
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>
因为在致电onNewIntent
后,onResume
被调用。