You can store the Tag in a field of the Activity. Doing this you can execute the logic of tag operations when the button is clicked. With these modifications, it should work:
public class MainActivity extends Activity {
private Tag mTag;
private IntentFilter[] mFilters;
private String[][] mTechLists;
private PendingIntent mPendingIntent;
private Button wbutton;
private NfcAdapter myNfcAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wbutton = (Button) findViewById(R.id.button1);
wbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
writeTag(mTag);
}
});
configureNfc();
}
private void configureNfc(){
myNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter intnfcv = new IntentFilter(
NfcAdapter.ACTION_TECH_DISCOVERED);
mFilters = new IntentFilter[] {
intnfcv};
mTechLists = new String[][] { new String[] {
NfcV.class.getName() }};
}
private synchronized void writeTag(Tag tag){
if(mTag !=null){
try {
new WriteVecinityTagTask().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
mTag=null;
}
}
@Override
public void onResume() {
super.onResume();
if (myNfcAdapter != null) {
myNfcAdapter.enableForegroundDispatch(this, mPendingIntent,
mFilters, mTechLists);
}
}
@Override
public void onPause() {
super.onPause();
myNfcAdapter.disableForegroundDispatch(this);
}
@Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
mTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
private class WriteVecinityTagTask extends AsyncTask<Void, Void, Boolean>{
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
String message = (result) ? "WRITE OK" : "ERROR";
Toast.makeText(MainActivity.this, message , Toast.LENGTH_SHORT).show();
}
@Override
protected Boolean doInBackground(Void... params) {
try{
NfcV vecinityTag = NfcV.get(mTag);
vecinityTag.connect();
vecinityTag.transceive(
new byte[] {0x00, 0x21, (byte) 0,0x31, 0x31, 0x31, 0x31}
);
vecinityTag.close();
}catch(IOException e){
e.printStackTrace();
return false;
}
return true;
}
}
}