我试图通过发送命令从nfcA标签中读取一些数据,然后每4秒钟获得一次响应。处理在从onNewIntent()调用的后台线程中完成。然后将使用一个处理程序来更新UI线程。到目前为止,这是我的代码。我很难让线程部分工作。没有从响应中获得任何更新。
当我卸载应用程序并重新启动手机时,我能够从标签中获得响应。让手机和标签保持连接会将响应发送几分钟。它抛出java.io.IOException, - 发送响应几分钟后 - 如果我将手机移离标签,然后尝试重新连接。
public class MainActivity extends ActionBarActivity {
private int PENDING_INTENT_TECH_DISCOVERED = 1;
private TextView mNfcTech, temp, vol, amb_temp;
private Utility myUtils = new Utility();
// Hold the 16 bytes response from the fast_read command
private byte[] response = new byte[16];
// Create a Handler object
private Handler handler = new Handler();
// Update interval
private int UPDATE_INTERVAL = 2000;
private static Tag detectedTag;
boolean threadRun = true;
public static final String TAG = "nfc";
private TextView mTextView;
private NfcAdapter mNfcAdapter;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialise the textview controls
mNfcTech = (TextView) findViewById(R.id.nfc_technology_tv);
temp = (TextView) findViewById(R.id.temp);
vol = (TextView) findViewById(R.id.vol);
amb_temp = (TextView) findViewById(R.id.amb_temp);
// Get the device nfc adpater
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (hasNfc()) {
Toast.makeText(this, "NFC is available.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "NFC is not available on this device. This application may not work correctly.", Toast.LENGTH_LONG).show();
}
// get the intent
Intent intent = getIntent();
String action =intent.getAction();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
// In case we would still use the Tech Discovered Intent
handleIntent(intent);
}
}
@Override
protected void onResume() {
super.onResume();
setupForegroundDispatch();
}
@Override
protected void onPause() {
/**
* Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
*/
stopForegroundDispatch();
super.onPause();
}
@Override
protected void onNewIntent(Intent intent) {
/**
* This method gets called, when a new Intent gets associated with the current activity instance.
* Instead of creating a new activity, onNewIntent will be called. Called
* when the user attaches a Tag to the device.
*/
handleIntent(intent);
}
// Handle the intent once tag comes in contact with phone
private void handleIntent(Intent intent) {
// TODO: handle Intent
String action = intent.getAction();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
// In case we would still use the Tech Discovered Intent
detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// start running the Thread
backgroundExecution();
}
}
public void setupForegroundDispatch() {
PendingIntent pi = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter techFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] intentFilter = new IntentFilter[]{techFilter};
String[][] techList = new String[][]{
new String[]{android.nfc.tech.NfcA.class.getName()}
};
mNfcAdapter.enableForegroundDispatch(this, pi, intentFilter, techList);
}
public void stopForegroundDispatch() {
mNfcAdapter.disableForegroundDispatch(this);
}
// Check if nfc is available for the device and is enabled.
public boolean hasNfc() {
boolean hasFeature = getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC);
boolean isEnabled = NfcAdapter.getDefaultAdapter(this).isEnabled();
return hasFeature && isEnabled;
}
public void backgroundExecution() {
// This moves the time consuming operation to a child thread.
Thread thread = new Thread(doBackgroundThreadProcessing);
thread.start();
}
// Runnable that executes the background processing method.
private Runnable doBackgroundThreadProcessing = new Runnable() {
public void run() {
NfcA nfca = NfcA.get(detectedTag);
// nfca fast_read command
byte[] command = new byte[]{0x3A, 0x04C, 0x04F};
// use for control stop/start of the thread
boolean keepRunning = true;
// run until as to stop
while(keepRunning){
// check if null
// if (nfca != null) {
if (!nfca.isConnected()){
try {
nfca.connect();
String TAG = "connect";
Log.i(TAG, "connected to the tag");
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.toString());
}
if (nfca.isConnected()) {
try {
// send command and get the response
response = nfca.transceive(command);
// log response to the console
String myStr = myUtils.bytesToHex(response);
String TAG = "fastRead";
Log.i(TAG, "Response receive :" + myStr);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.toString());
} finally {
try {
nfca.close();
// log closing to the console
String TAG = "close";
Log.i(TAG,"closing the connection");
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.toString());
}
// stop the
// keepRunning = false;
// put the thread to sleep for 4 sec
try {
Thread.sleep(4000);
} catch (InterruptedException e) {e.printStackTrace();}
}
}
}
}
}
};
}
`