1 package skyseraph.easytagwrite; 2 3 import skyseraph.android.util.CustomDialog; 4 import skyseraph.android.util.LogUtil; 5 import skyseraph.android.util.MyConstant; 6 import skyseraph.android.util.nfc.BobNdefMessage; 7 8 import android.app.Activity; 9 import android.app.AlertDialog; 10 import android.app.Dialog; 11 import android.app.PendingIntent; 12 import android.content.Context; 13 import android.content.DialogInterface; 14 import android.content.Intent; 15 import android.content.IntentFilter; 16 import android.graphics.Color; 17 import android.nfc.NdefMessage; 18 import android.nfc.NfcAdapter; 19 import android.nfc.Tag; 20 import android.nfc.tech.Ndef; 21 import android.nfc.tech.NdefFormatable; 22 import android.os.AsyncTask; 23 import android.os.Bundle; 24 import android.provider.Settings; 25 import android.util.DisplayMetrics; 26 import android.view.Menu; 27 import android.view.MenuItem; 28 import android.view.View; 29 import android.view.WindowManager; 30 import android.widget.AdapterView; 31 import android.widget.AdapterView.OnItemSelectedListener; 32 import android.widget.ArrayAdapter; 33 import android.widget.Button; 34 import android.widget.EditText; 35 import android.widget.Spinner; 36 import android.widget.TextView; 37 import android.widget.Toast; 38 39 import java.io.IOException; 40 41 public class MainActivity extends Activity { 42 private static final String TAG_ASSIST = "[MainActivity]-"; 43 44 // NFC Declarations 45 private NfcAdapter mNfcAdapter = null; 46 47 private IntentFilter[] mFilters = null; 48 49 private PendingIntent mPendingIntent = null; 50 51 private String[][] mTechLists = null; 52 53 private Context mContext; 54 55 private NdefMessage NDEFMsg2Write = null; 56 57 // UI 58 private EditText mEditText1 = null; 59 60 private EditText mEditText2 = null; 61 62 private TextView mTextView1 = null; 63 64 private TextView mTextView2 = null; 65 66 private Spinner mSpinner = null; 67 68 private ArrayAdapter mAdapter = null; 69 70 private Button writeUrlButton, saveUrlButton, exitButton; 71 72 private static final String[] spinnerStr = { 73 "TNF_ABSOLUTE_URI", "TNF_MIME_MEDIA", "TNF_WELL_KNOWN RTD-TEXT", 74 "TNF_WELL_KNOWN RTD-URI", "TNF_EXTERNAL_TYPE", 75 }; 76 77 private String payloadStr = ""; 78 79 private String typeStr = ""; 80 81 private int tagTypeFlag = 0;// 82 83 private AlertDialog alertDialog = null; 84 85 @Override 86 protected void onCreate(Bundle savedInstanceState) { 87 super.onCreate(savedInstanceState); 88 setContentView(R.layout.activity_main); 89 mContext = this; 90 91 checkNFCFunction(); // NFC Check 92 initUI();// Init UI 93 initNFC();// Init NFC 94 } 95 96 @Override 97 public boolean onCreateOptionsMenu(Menu menu) { 98 // Inflate the menu; this adds items to the action bar if it is present. 99 getMenuInflater().inflate(R.menu.main, menu); 100 return true; 101 } 102 103 @Override 104 public boolean onOptionsItemSelected(MenuItem item) { 105 // TODO Auto-generated method stub 106 super.onOptionsItemSelected(item); 107 switch (item.getItemId()) 108 // item clicked 109 { 110 case R.id.action_settings: 111 // Intent setnfc = new 112 // Intent(Settings.ACTION_WIRELESS_SETTINGS); 113 Intent setnfc = new Intent(Settings.ACTION_NFC_SETTINGS); 114 startActivity(setnfc); 115 break; 116 case R.id.action_about: 117 dialog(); 118 break; 119 } 120 return true; 121 } 122 123 protected void dialog() { 124 AlertDialog.Builder builder = new AlertDialog.Builder(mContext); 125 builder.setTitle(getString(R.string.dialog_notice)); 126 alertDialog = builder.create(); 127 builder.setCancelable(true);// back 128 alertDialog.setCanceledOnTouchOutside(true); 129 alertDialog.show(); 130 } 131 132 @Override 133 public void onResume() { 134 super.onResume(); 135 if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) { 136 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "ACTION_TECH_DISCOVERED"); 137 // get NFC object 138 Tag detectTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG); 139 // validate that this tag can be written 140 if (supportedTechs(detectTag.getTechList())) { 141 switch (tagTypeFlag) { 142 case 0:// ABSOLUTE_URI 143 NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_ABSOLUTE_URI(payloadStr, false); 144 // writeNdefMessageToTag(NDEFMsg2Write, detectTag); // By 145 // Function 146 new WriteTask(this, NDEFMsg2Write, detectTag).execute(); // By 147 // AsyncTask 148 // Class 149 break; 150 case 1:// MIME_MEDIA 151 NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_MIME_MEDIA(payloadStr, 152 "application/skyseraph.nfc_demo", false); 153 // writeNdefMessageToTag(NDEFMsg2Write, detectTag); 154 new WriteTask(this, NDEFMsg2Write, detectTag).execute(); 155 break; 156 case 2:// RTD_TEXT 157 NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_RTD_TEXT(payloadStr, false, 158 false); 159 // writeNdefMessageToTag(NDEFMsg2Write, detectTag); 160 new WriteTask(this, NDEFMsg2Write, detectTag).execute(); 161 break; 162 case 3:// RTD_URI 163 NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_RTD_URI(payloadStr, (byte)0x01, 164 false); 165 // writeNdefMessageToTag(NDEFMsg2Write, detectTag); 166 new WriteTask(this, NDEFMsg2Write, detectTag).execute(); 167 break; 168 case 4:// EXTERNAL_TYPE 169 NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_EXTERNAL_TYPE(payloadStr, false); 170 // writeNdefMessageToTag(NDEFMsg2Write, detectTag); 171 new WriteTask(this, NDEFMsg2Write, detectTag).execute(); 172 break; 173 default:// RTD_URI 174 NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_RTD_URI(payloadStr, (byte)0x01, 175 false); 176 // writeNdefMessageToTag(NDEFMsg2Write, detectTag); 177 new WriteTask(this, NDEFMsg2Write, detectTag).execute(); 178 break; 179 } 180 } else { 181 Toast.makeText(mContext, "This tag type is not supported", Toast.LENGTH_SHORT).show(); 182 } 183 } 184 } 185 186 @Override 187 public void onNewIntent(Intent intent) { 188 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "Discovered tag with intent: " + intent); 189 setIntent(intent); 190 } 191 192 @Override 193 public void onPause() { 194 super.onPause(); 195 if (alertDialog != null) 196 alertDialog.cancel(); 197 disableForegroundDispatch(); 198 } 199 200 private void initUI() { 201 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into initUI"); 202 // TODO Auto-generated method stub 203 mEditText1 = (EditText)this.findViewById(R.id.write_ndef_tag_et1); 204 mEditText2 = (EditText)this.findViewById(R.id.write_ndef_tag_et2); 205 mTextView1 = (TextView)findViewById(R.id.write_ndef_tag_tv1); 206 mTextView2 = (TextView)findViewById(R.id.write_ndef_tag_tv2); 207 208 saveUrlButton = (Button)findViewById(R.id.write_ndef_tag_saveBtn); 209 saveUrlButton.setOnClickListener(new View.OnClickListener() { 210 public void onClick(View v) { 211 writeUrlButton.setEnabled(true); 212 switch (tagTypeFlag) { 213 case 0:// ABSOLUTE_URI 214 payloadStr = mEditText1.getText().toString(); 215 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); 216 mTextView1.setText("(Touch NFC Tag to write-ABSOLUTE_URI): " + payloadStr); 217 mTextView1.setTextColor(Color.BLUE); 218 break; 219 case 1:// MIME_MEDIA 220 payloadStr = mEditText2.getText().toString(); 221 typeStr = mEditText1.getText().toString(); 222 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr 223 + ",typeStr=" + typeStr); 224 mTextView1.setText("Touch NFC Tag to write-MIME_MEDIA): " + typeStr); 225 mTextView1.setTextColor(Color.BLUE); 226 mTextView2 227 .setText("Touch NFC Tag to write-MIME_MEDIA,Data): " + payloadStr); 228 mTextView2.setTextColor(Color.BLUE); 229 break; 230 case 2:// RTD_TEXT 231 payloadStr = mEditText1.getText().toString(); 232 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); 233 mTextView1.setText("(Touch NFC Tag to write-RTD_TEXT): " + payloadStr); 234 mTextView1.setTextColor(Color.BLUE); 235 break; 236 case 3:// RTD_URI 237 payloadStr = mEditText1.getText().toString(); 238 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); 239 mTextView1.setText("(Touch NFC Tag to write-RTD_URI): http://www." 240 + payloadStr); 241 mTextView1.setTextColor(Color.BLUE); 242 break; 243 case 4:// EXTERNAL_TYPE_SMS 244 typeStr = "skyseraph.nfc_demo:externalType"; 245 payloadStr = mEditText2.getText().toString(); 246 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); 247 mTextView1.setText("Touch NFC Tag to write-EXTERNAL_TYPE): " + payloadStr); 248 mTextView1.setTextColor(Color.BLUE); 249 break; 250 default:// RTD_URI 251 payloadStr = mEditText1.getText().toString(); 252 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); 253 mTextView1.setText("(Touch NFC Tag to write): http://www." + payloadStr); 254 mTextView1.setTextColor(Color.BLUE); 255 break; 256 } 257 } 258 }); 259 260 writeUrlButton = (Button)this.findViewById(R.id.write_ndef_tag_writeBtn); 261 writeUrlButton.setEnabled(false); 262 writeUrlButton.setOnClickListener(new View.OnClickListener() { 263 public void onClick(View view) { 264 // Write to a tag for as long as the dialog is shown. 265 enableForegroundDispatch(); 266 AlertDialog.Builder builder = new AlertDialog.Builder(mContext); 267 builder.setTitle("Touch tag to write").setOnCancelListener( 268 new DialogInterface.OnCancelListener() { 269 @Override 270 public void onCancel(DialogInterface dialog) { 271 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "mTagWriter - onCancel"); 272 disableForegroundDispatch(); 273 } 274 }); 275 alertDialog = builder.create(); 276 alertDialog.setCanceledOnTouchOutside(false); 277 alertDialog.show(); 278 } 279 }); 280 281 exitButton = (Button)findViewById(R.id.write_ndef_tag_exitBtn); 282 exitButton.setOnClickListener(new View.OnClickListener() { 283 public void onClick(View v) { 284 finish(); 285 } 286 }); 287 288 mSpinner = (Spinner)findViewById(R.id.write_ndef_tag_sp); 289 mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerStr); 290 mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 291 mSpinner.setAdapter(mAdapter); 292 mSpinner.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); 293 mSpinner.setVisibility(View.VISIBLE); 294 mSpinner.setSelection(0, true); 295 } 296 297 class SpinnerXMLSelectedListener implements OnItemSelectedListener { 298 public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 299 LogUtil.i(MyConstant.TAG, 300 TAG_ASSIST + "What you have selected=" + mAdapter.getItem(arg2) + ",position=" 301 + arg2); 302 saveUrlButton.setEnabled(true); 303 writeUrlButton.setEnabled(false); 304 switch (arg2) { 305 case 0:// ABSOLUTE_URI 306 tagTypeFlag = 0; 307 mTextView1 308 .setText("Please input a absolute uri,exp: http://www.baidu.com/index.html"); 309 mTextView1.setTextColor(Color.RED); 310 mEditText2.setVisibility(View.GONE); 311 mTextView2.setVisibility(View.GONE); 312 break; 313 case 1:// MIME_MEDIA 314 tagTypeFlag = 1; 315 mTextView2 316 .setText("Please input a mime_media, exp: application/skyseraph.nfc_demo"); 317 mTextView1.setTextColor(Color.RED); 318 mEditText2.setVisibility(View.VISIBLE); 319 mTextView2.setVisibility(View.VISIBLE); 320 mTextView1 321 .setText("Please input your mime_media data, exp: This is a MIME_MEDIA"); 322 mTextView2.setTextColor(Color.RED); 323 break; 324 case 2:// RTD TEXT 325 tagTypeFlag = 2; 326 mTextView1.setText("Please input a RTD TEXT,exp: This is an RTD-TEXT"); 327 mTextView1.setTextColor(Color.RED); 328 mEditText2.setVisibility(View.GONE); 329 mTextView2.setVisibility(View.GONE); 330 break; 331 case 3: // RTD URI 332 tagTypeFlag = 3; 333 mTextView1.setText("Please input a RTD uri,exp: baidu.com"); 334 mTextView1.setTextColor(Color.RED); 335 mEditText2.setVisibility(View.GONE); 336 mTextView2.setVisibility(View.GONE); 337 break; 338 case 4:// EXTERNAL_TYPE 339 tagTypeFlag = 4; 340 mTextView1 341 .setText("Please input a EXTERNAL_TYPE, exp: This is an EXTERNAL_TYPE"); 342 mTextView1.setTextColor(Color.RED); 343 mEditText2.setVisibility(View.GONE); 344 mTextView2.setVisibility(View.GONE); 345 break; 346 default:// RTD_URI 347 tagTypeFlag = 3; 348 mTextView1.setText("Please input a RTD uri,exp: baidu.com"); 349 mTextView1.setTextColor(Color.RED); 350 mEditText2.setVisibility(View.GONE); 351 mTextView2.setVisibility(View.GONE); 352 break; 353 } 354 } 355 356 public void onNothingSelected(AdapterView<?> arg0) { 357 358 } 359 } 360 361 /** 362 * Init NFC 363 */ 364 private void initNFC() { 365 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into initNFC"); 366 mPendingIntent = PendingIntent.getActivity(this, 0, 367 new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 368 // FLAG_ACTIVITY_SINGLE_TOP: not creating multiple instances of the same 369 // application. 370 IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); 371 IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); 372 IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED); 373 // ndef.addDataScheme("http"); 374 // Intent filters for writing to a tag 375 mFilters = new IntentFilter[] { 376 ndefDetected, 377 };// just trying to find a tag,not ndef or tech 378 379 mTechLists = new String[][] { 380 new String[] { 381 Ndef.class.getName() 382 }, new String[] { 383 NdefFormatable.class.getName() 384 } 385 }; 386 } 387 388 /** 389 * @param message 390 * @param detectedTag 391 * @return 392 */ 393 boolean writeNdefMessageToTag(NdefMessage message, Tag detectedTag) { 394 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into writeNdefMessageToTag"); 395 int size = message.toByteArray().length; 396 try { 397 Ndef ndef = Ndef.get(detectedTag); 398 if (ndef != null) { 399 ndef.connect(); 400 401 if (!ndef.isWritable()) { 402 Toast.makeText(this, "Tag is read-only.", Toast.LENGTH_LONG).show(); 403 return false; 404 } 405 if (ndef.getMaxSize() < size) { 406 Toast.makeText( 407 this, 408 "The data cannot written to tag, Tag capacity is " + ndef.getMaxSize() 409 + " bytes, message is " + size + " bytes.", Toast.LENGTH_LONG) 410 .show(); 411 return false; 412 } 413 414 ndef.writeNdefMessage(message); 415 ndef.close(); 416 String str = "Message is written tag, message=" + message; 417 Toast.makeText(this, str, Toast.LENGTH_LONG).show(); 418 return true; 419 } else { 420 NdefFormatable ndefFormat = NdefFormatable.get(detectedTag); 421 if (ndefFormat != null) { 422 try { 423 ndefFormat.connect(); 424 ndefFormat.format(message); 425 ndefFormat.close(); 426 Toast.makeText(this, "The data is written to the tag ", Toast.LENGTH_SHORT) 427 .show(); 428 return true; 429 } catch (IOException e) { 430 Toast.makeText(this, "Failed to format tag", Toast.LENGTH_SHORT).show(); 431 return false; 432 } 433 } else { 434 Toast.makeText(this, "NDEF is not supported", Toast.LENGTH_SHORT).show(); 435 return false; 436 } 437 } 438 } catch (Exception e) { 439 Toast.makeText(this, "Write opreation is failed", Toast.LENGTH_SHORT).show(); 440 } 441 return false; 442 } 443 444 /** 445 * @Title: supportedTechs 446 * @Description: Check Support Techs 447 * @param @param techs 448 * @param @return 449 * @return boolean 450 * @throws 451 */ 452 public static boolean supportedTechs(String[] techs) { 453 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into supportedTechs"); 454 for (String s : techs) { 455 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "all supportedTechs = " + s); 456 } 457 boolean ultralight = false; 458 boolean nfcA = false; 459 boolean ndef = false; 460 for (String tech : techs) { 461 if (tech.equals("android.nfc.tech.MifareUltralight")) { 462 ultralight = true; 463 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:ultralight"); 464 } else if (tech.equals("android.nfc.tech.NfcA")) { 465 nfcA = true; 466 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:NfcA"); 467 } else if (tech.equals("android.nfc.tech.Ndef") 468 || tech.equals("android.nfc.tech.NdefFormatable")) { 469 ndef = true; 470 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:Ndef/NdefFormatable"); 471 } else if (tech.equals("android.nfc.tech.MifareClassic")) { 472 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:MifareClassic"); 473 } 474 } 475 if (ultralight && nfcA && ndef) { 476 return true; 477 } else { 478 return false; 479 } 480 } 481 482 /** 483 * enable TagWrite 484 */ 485 private void enableForegroundDispatch() { 486 if (mNfcAdapter != null) { 487 mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists); 488 } 489 } 490 491 /** 492 * disable TagWrite 493 */ 494 private void disableForegroundDispatch() { 495 if (mNfcAdapter != null) { 496 mNfcAdapter.disableForegroundDispatch(this); 497 } 498 } 499 500 /** 501 * NFC Function Check By skyseraph 2013-2 502 */ 503 private void checkNFCFunction() { 504 // TODO Auto-generated method stub 505 mNfcAdapter = NfcAdapter.getDefaultAdapter(this); 506 // check the NFC adapter first 507 if (mNfcAdapter == null) { 508 // mTextView.setText("NFC apdater is not available"); 509 Dialog dialog = null; 510 CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); 511 customBuilder 512 .setTitle(getString(R.string.inquire)) 513 .setMessage(getString(R.string.nfc_notice2)) 514 .setIcon(R.drawable.dialog_icon2) 515 .setNegativeButton(getString(R.string.no), 516 new DialogInterface.OnClickListener() { 517 public void onClick(DialogInterface dialog, int which) { 518 dialog.dismiss(); 519 finish(); 520 } 521 }) 522 .setPositiveButton(getString(R.string.yes), 523 new DialogInterface.OnClickListener() { 524 public void onClick(DialogInterface dialog, int which) { 525 dialog.dismiss(); 526 finish(); 527 } 528 }); 529 dialog = customBuilder.create(); 530 dialog.setCancelable(false);// back 531 dialog.setCanceledOnTouchOutside(false); 532 SetDialogWidth(dialog).show(); 533 return; 534 } else { 535 if (!mNfcAdapter.isEnabled()) { 536 Dialog dialog = null; 537 CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); 538 customBuilder 539 .setTitle(getString(R.string.inquire)) 540 .setMessage(getString(R.string.nfc_notice3)) 541 .setIcon(R.drawable.dialog_icon2) 542 .setNegativeButton(getString(R.string.no), 543 new DialogInterface.OnClickListener() { 544 public void onClick(DialogInterface dialog, int which) { 545 dialog.dismiss(); 546 finish(); 547 } 548 }) 549 .setPositiveButton(getString(R.string.yes), 550 new DialogInterface.OnClickListener() { 551 public void onClick(DialogInterface dialog, int which) { 552 dialog.dismiss(); 553 Intent setnfc = new Intent( 554 Settings.ACTION_WIRELESS_SETTINGS); 555 // Intent setnfc = new 556 // Intent(Settings.ACTION_NFC_SETTINGS); 557 startActivity(setnfc); 558 } 559 }); 560 dialog = customBuilder.create(); 561 dialog.setCancelable(false);// back 562 dialog.setCanceledOnTouchOutside(false); 563 SetDialogWidth(dialog).show(); 564 return; 565 } 566 } 567 } 568 569 /** 570 * @param dialog 571 * @return 572 */ 573 private Dialog SetDialogWidth(Dialog dialog) { 574 DisplayMetrics dm = new DisplayMetrics(); 575 getWindowManager().getDefaultDisplay().getMetrics(dm); 576 int screenWidth = dm.widthPixels; 577 int screenHeight = dm.heightPixels; 578 WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); 579 if (screenWidth > screenHeight) { 580 params.width = (int)(((float)screenHeight) * 0.875); 581 582 } else { 583 params.width = (int)(((float)screenWidth) * 0.875); 584 } 585 dialog.getWindow().setAttributes(params); 586 587 return dialog; 588 } 589 590 /** 591 *********************************************************************** @Title :WriteNdefTag.java 592 * @Package :skyseraph.nfc_demo.tag.write 593 * @ClassName : WriteTask 594 * @Description : TODO 595 * @author : skyseraph00@163.com 596 * @date : 2013-9-13 上午11:38:58 597 * @version : V1.0 598 */ 599 static class WriteTask extends AsyncTask<Void, Void, Void> { 600 Activity host = null; 601 602 NdefMessage msg = null; 603 604 Tag tag = null; 605 606 String text = null; 607 608 WriteTask(Activity host, NdefMessage msg, Tag tag) { 609 LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into WriteTask AsyncTask"); 610 this.host = host; 611 this.msg = msg; 612 this.tag = tag; 613 } 614 615 @Override 616 protected Void doInBackground(Void... arg0) { 617 int size = msg.toByteArray().length; 618 619 try { 620 Ndef ndef = Ndef.get(tag); 621 622 if (ndef == null) { 623 NdefFormatable formatable = NdefFormatable.get(tag); 624 if (formatable != null) { 625 try { 626 formatable.connect(); 627 try { 628 formatable.format(msg); 629 } catch (Exception e) { 630 text = "Failed to format tag,Tag refused to format"; 631 } 632 } catch (Exception e) { 633 text = "Failed to connect tag,Tag refused to connect"; 634 } finally { 635 formatable.close(); 636 } 637 } else { 638 text = "NDEF is not supported in this Tag"; 639 } 640 } else { 641 ndef.connect(); 642 643 try { 644 if (!ndef.isWritable()) { 645 text = "Tag is read-only"; 646 } else if (ndef.getMaxSize() < size) { 647 text = "The data cannot written to tag,Message is too big for tag,Tag capacity is " 648 + ndef.getMaxSize() + " bytes, message is " + size + " bytes."; 649 } else { 650 ndef.writeNdefMessage(msg); 651 text = "Message is written tag, message=" + msg; 652 } 653 } catch (Exception e) { 654 text = "Tag refused to connect"; 655 } finally { 656 ndef.close(); 657 } 658 } 659 } catch (Exception e) { 660 text = "Write opreation is failed,General exception: " + e.getMessage(); 661 LogUtil.i(MyConstant.TAG, TAG_ASSIST 662 + "Exception when writing tag,Write opreation is failed" + text); 663 } 664 665 return (null); 666 } 667 668 @Override 669 protected void onPostExecute(Void unused) { 670 if (text != null) { 671 Toast.makeText(host, text, Toast.LENGTH_SHORT).show(); 672 } 673 674 // host.finish(); // after writed, auto finish 675 } 676 } 677 }
package skyseraph.easytagwrite;
import skyseraph.android.util.CustomDialog;import skyseraph.android.util.LogUtil;import skyseraph.android.util.MyConstant;import skyseraph.android.util.nfc.BobNdefMessage;
import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.PendingIntent;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.IntentFilter;import android.graphics.Color;import android.nfc.NdefMessage;import android.nfc.NfcAdapter;import android.nfc.Tag;import android.nfc.tech.Ndef;import android.nfc.tech.NdefFormatable;import android.os.AsyncTask;import android.os.Bundle;import android.provider.Settings;import android.util.DisplayMetrics;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.WindowManager;import android.widget.AdapterView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.Spinner;import android.widget.TextView;import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity { private static final String TAG_ASSIST = "[MainActivity]-";
// NFC Declarations private NfcAdapter mNfcAdapter = null;
private IntentFilter[] mFilters = null;
private PendingIntent mPendingIntent = null;
private String[][] mTechLists = null;
private Context mContext;
private NdefMessage NDEFMsg2Write = null;
// UI private EditText mEditText1 = null;
private EditText mEditText2 = null;
private TextView mTextView1 = null;
private TextView mTextView2 = null;
private Spinner mSpinner = null;
private ArrayAdapter mAdapter = null;
private Button writeUrlButton, saveUrlButton, exitButton;
private static final String[] spinnerStr = { "TNF_ABSOLUTE_URI", "TNF_MIME_MEDIA", "TNF_WELL_KNOWN RTD-TEXT", "TNF_WELL_KNOWN RTD-URI", "TNF_EXTERNAL_TYPE", };
private String payloadStr = "";
private String typeStr = "";
private int tagTypeFlag = 0;//
private AlertDialog alertDialog = null;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this;
checkNFCFunction(); // NFC Check initUI();// Init UI initNFC();// Init NFC }
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }
@Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub super.onOptionsItemSelected(item); switch (item.getItemId()) // item clicked { case R.id.action_settings: // Intent setnfc = new // Intent(Settings.ACTION_WIRELESS_SETTINGS); Intent setnfc = new Intent(Settings.ACTION_NFC_SETTINGS); startActivity(setnfc); break; case R.id.action_about: dialog(); break; } return true; }
protected void dialog() { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle(getString(R.string.dialog_notice)); alertDialog = builder.create(); builder.setCancelable(true);// back alertDialog.setCanceledOnTouchOutside(true); alertDialog.show(); }
@Override public void onResume() { super.onResume(); if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "ACTION_TECH_DISCOVERED"); // get NFC object Tag detectTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG); // validate that this tag can be written if (supportedTechs(detectTag.getTechList())) { switch (tagTypeFlag) { case 0:// ABSOLUTE_URI NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_ABSOLUTE_URI(payloadStr, false); // writeNdefMessageToTag(NDEFMsg2Write, detectTag); // By // Function new WriteTask(this, NDEFMsg2Write, detectTag).execute(); // By // AsyncTask // Class break; case 1:// MIME_MEDIA NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_MIME_MEDIA(payloadStr, "application/skyseraph.nfc_demo", false); // writeNdefMessageToTag(NDEFMsg2Write, detectTag); new WriteTask(this, NDEFMsg2Write, detectTag).execute(); break; case 2:// RTD_TEXT NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_RTD_TEXT(payloadStr, false, false); // writeNdefMessageToTag(NDEFMsg2Write, detectTag); new WriteTask(this, NDEFMsg2Write, detectTag).execute(); break; case 3:// RTD_URI NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_RTD_URI(payloadStr, (byte)0x01, false); // writeNdefMessageToTag(NDEFMsg2Write, detectTag); new WriteTask(this, NDEFMsg2Write, detectTag).execute(); break; case 4:// EXTERNAL_TYPE NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_EXTERNAL_TYPE(payloadStr, false); // writeNdefMessageToTag(NDEFMsg2Write, detectTag); new WriteTask(this, NDEFMsg2Write, detectTag).execute(); break; default:// RTD_URI NDEFMsg2Write = BobNdefMessage.getNdefMsg_from_RTD_URI(payloadStr, (byte)0x01, false); // writeNdefMessageToTag(NDEFMsg2Write, detectTag); new WriteTask(this, NDEFMsg2Write, detectTag).execute(); break; } } else { Toast.makeText(mContext, "This tag type is not supported", Toast.LENGTH_SHORT).show(); } } }
@Override public void onNewIntent(Intent intent) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "Discovered tag with intent: " + intent); setIntent(intent); }
@Override public void onPause() { super.onPause(); if (alertDialog != null) alertDialog.cancel(); disableForegroundDispatch(); }
private void initUI() { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into initUI"); // TODO Auto-generated method stub mEditText1 = (EditText)this.findViewById(R.id.write_ndef_tag_et1); mEditText2 = (EditText)this.findViewById(R.id.write_ndef_tag_et2); mTextView1 = (TextView)findViewById(R.id.write_ndef_tag_tv1); mTextView2 = (TextView)findViewById(R.id.write_ndef_tag_tv2);
saveUrlButton = (Button)findViewById(R.id.write_ndef_tag_saveBtn); saveUrlButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { writeUrlButton.setEnabled(true); switch (tagTypeFlag) { case 0:// ABSOLUTE_URI payloadStr = mEditText1.getText().toString(); LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); mTextView1.setText("(Touch NFC Tag to write-ABSOLUTE_URI): " + payloadStr); mTextView1.setTextColor(Color.BLUE); break; case 1:// MIME_MEDIA payloadStr = mEditText2.getText().toString(); typeStr = mEditText1.getText().toString(); LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr + ",typeStr=" + typeStr); mTextView1.setText("Touch NFC Tag to write-MIME_MEDIA): " + typeStr); mTextView1.setTextColor(Color.BLUE); mTextView2 .setText("Touch NFC Tag to write-MIME_MEDIA,Data): " + payloadStr); mTextView2.setTextColor(Color.BLUE); break; case 2:// RTD_TEXT payloadStr = mEditText1.getText().toString(); LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); mTextView1.setText("(Touch NFC Tag to write-RTD_TEXT): " + payloadStr); mTextView1.setTextColor(Color.BLUE); break; case 3:// RTD_URI payloadStr = mEditText1.getText().toString(); LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); mTextView1.setText("(Touch NFC Tag to write-RTD_URI): http://www." + payloadStr); mTextView1.setTextColor(Color.BLUE); break; case 4:// EXTERNAL_TYPE_SMS typeStr = "skyseraph.nfc_demo:externalType"; payloadStr = mEditText2.getText().toString(); LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); mTextView1.setText("Touch NFC Tag to write-EXTERNAL_TYPE): " + payloadStr); mTextView1.setTextColor(Color.BLUE); break; default:// RTD_URI payloadStr = mEditText1.getText().toString(); LogUtil.i(MyConstant.TAG, TAG_ASSIST + "payloadStr=" + payloadStr); mTextView1.setText("(Touch NFC Tag to write): http://www." + payloadStr); mTextView1.setTextColor(Color.BLUE); break; } } });
writeUrlButton = (Button)this.findViewById(R.id.write_ndef_tag_writeBtn); writeUrlButton.setEnabled(false); writeUrlButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Write to a tag for as long as the dialog is shown. enableForegroundDispatch(); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("Touch tag to write").setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "mTagWriter - onCancel"); disableForegroundDispatch(); } }); alertDialog = builder.create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); } });
exitButton = (Button)findViewById(R.id.write_ndef_tag_exitBtn); exitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } });
mSpinner = (Spinner)findViewById(R.id.write_ndef_tag_sp); mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerStr); mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpinner.setAdapter(mAdapter); mSpinner.setOnItemSelectedListener(new SpinnerXMLSelectedListener()); mSpinner.setVisibility(View.VISIBLE); mSpinner.setSelection(0, true); }
class SpinnerXMLSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "What you have selected=" + mAdapter.getItem(arg2) + ",position=" + arg2); saveUrlButton.setEnabled(true); writeUrlButton.setEnabled(false); switch (arg2) { case 0:// ABSOLUTE_URI tagTypeFlag = 0; mTextView1 .setText("Please input a absolute uri,exp: http://www.baidu.com/index.html"); mTextView1.setTextColor(Color.RED); mEditText2.setVisibility(View.GONE); mTextView2.setVisibility(View.GONE); break; case 1:// MIME_MEDIA tagTypeFlag = 1; mTextView2 .setText("Please input a mime_media, exp: application/skyseraph.nfc_demo"); mTextView1.setTextColor(Color.RED); mEditText2.setVisibility(View.VISIBLE); mTextView2.setVisibility(View.VISIBLE); mTextView1 .setText("Please input your mime_media data, exp: This is a MIME_MEDIA"); mTextView2.setTextColor(Color.RED); break; case 2:// RTD TEXT tagTypeFlag = 2; mTextView1.setText("Please input a RTD TEXT,exp: This is an RTD-TEXT"); mTextView1.setTextColor(Color.RED); mEditText2.setVisibility(View.GONE); mTextView2.setVisibility(View.GONE); break; case 3: // RTD URI tagTypeFlag = 3; mTextView1.setText("Please input a RTD uri,exp: baidu.com"); mTextView1.setTextColor(Color.RED); mEditText2.setVisibility(View.GONE); mTextView2.setVisibility(View.GONE); break; case 4:// EXTERNAL_TYPE tagTypeFlag = 4; mTextView1 .setText("Please input a EXTERNAL_TYPE, exp: This is an EXTERNAL_TYPE"); mTextView1.setTextColor(Color.RED); mEditText2.setVisibility(View.GONE); mTextView2.setVisibility(View.GONE); break; default:// RTD_URI tagTypeFlag = 3; mTextView1.setText("Please input a RTD uri,exp: baidu.com"); mTextView1.setTextColor(Color.RED); mEditText2.setVisibility(View.GONE); mTextView2.setVisibility(View.GONE); break; } }
public void onNothingSelected(AdapterView<?> arg0) {
} }
/** * Init NFC */ private void initNFC() { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into initNFC"); mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); // FLAG_ACTIVITY_SINGLE_TOP: not creating multiple instances of the same // application. IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED); // ndef.addDataScheme("http"); // Intent filters for writing to a tag mFilters = new IntentFilter[] { ndefDetected, };// just trying to find a tag,not ndef or tech
mTechLists = new String[][] { new String[] { Ndef.class.getName() }, new String[] { NdefFormatable.class.getName() } }; }
/** * @param message * @param detectedTag * @return */ boolean writeNdefMessageToTag(NdefMessage message, Tag detectedTag) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into writeNdefMessageToTag"); int size = message.toByteArray().length; try { Ndef ndef = Ndef.get(detectedTag); if (ndef != null) { ndef.connect();
if (!ndef.isWritable()) { Toast.makeText(this, "Tag is read-only.", Toast.LENGTH_LONG).show(); return false; } if (ndef.getMaxSize() < size) { Toast.makeText( this, "The data cannot written to tag, Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.", Toast.LENGTH_LONG) .show(); return false; }
ndef.writeNdefMessage(message); ndef.close(); String str = "Message is written tag, message=" + message; Toast.makeText(this, str, Toast.LENGTH_LONG).show(); return true; } else { NdefFormatable ndefFormat = NdefFormatable.get(detectedTag); if (ndefFormat != null) { try { ndefFormat.connect(); ndefFormat.format(message); ndefFormat.close(); Toast.makeText(this, "The data is written to the tag ", Toast.LENGTH_SHORT) .show(); return true; } catch (IOException e) { Toast.makeText(this, "Failed to format tag", Toast.LENGTH_SHORT).show(); return false; } } else { Toast.makeText(this, "NDEF is not supported", Toast.LENGTH_SHORT).show(); return false; } } } catch (Exception e) { Toast.makeText(this, "Write opreation is failed", Toast.LENGTH_SHORT).show(); } return false; }
/** * @Title: supportedTechs * @Description: Check Support Techs * @param @param techs * @param @return * @return boolean * @throws */ public static boolean supportedTechs(String[] techs) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into supportedTechs"); for (String s : techs) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "all supportedTechs = " + s); } boolean ultralight = false; boolean nfcA = false; boolean ndef = false; for (String tech : techs) { if (tech.equals("android.nfc.tech.MifareUltralight")) { ultralight = true; LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:ultralight"); } else if (tech.equals("android.nfc.tech.NfcA")) { nfcA = true; LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:NfcA"); } else if (tech.equals("android.nfc.tech.Ndef") || tech.equals("android.nfc.tech.NdefFormatable")) { ndef = true; LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:Ndef/NdefFormatable"); } else if (tech.equals("android.nfc.tech.MifareClassic")) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "supportedTechs is:MifareClassic"); } } if (ultralight && nfcA && ndef) { return true; } else { return false; } }
/** * enable TagWrite */ private void enableForegroundDispatch() { if (mNfcAdapter != null) { mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists); } }
/** * disable TagWrite */ private void disableForegroundDispatch() { if (mNfcAdapter != null) { mNfcAdapter.disableForegroundDispatch(this); } }
/** * NFC Function Check By skyseraph 2013-2 */ private void checkNFCFunction() { // TODO Auto-generated method stub mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // check the NFC adapter first if (mNfcAdapter == null) { // mTextView.setText("NFC apdater is not available"); Dialog dialog = null; CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder .setTitle(getString(R.string.inquire)) .setMessage(getString(R.string.nfc_notice2)) .setIcon(R.drawable.dialog_icon2) .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }) .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); dialog = customBuilder.create(); dialog.setCancelable(false);// back dialog.setCanceledOnTouchOutside(false); SetDialogWidth(dialog).show(); return; } else { if (!mNfcAdapter.isEnabled()) { Dialog dialog = null; CustomDialog.Builder customBuilder = new CustomDialog.Builder(mContext); customBuilder .setTitle(getString(R.string.inquire)) .setMessage(getString(R.string.nfc_notice3)) .setIcon(R.drawable.dialog_icon2) .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }) .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent setnfc = new Intent( Settings.ACTION_WIRELESS_SETTINGS); // Intent setnfc = new // Intent(Settings.ACTION_NFC_SETTINGS); startActivity(setnfc); } }); dialog = customBuilder.create(); dialog.setCancelable(false);// back dialog.setCanceledOnTouchOutside(false); SetDialogWidth(dialog).show(); return; } } }
/** * @param dialog * @return */ private Dialog SetDialogWidth(Dialog dialog) { DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int screenWidth = dm.widthPixels; int screenHeight = dm.heightPixels; WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); if (screenWidth > screenHeight) { params.width = (int)(((float)screenHeight) * 0.875);
} else { params.width = (int)(((float)screenWidth) * 0.875); } dialog.getWindow().setAttributes(params);
return dialog; }
/** *********************************************************************** @Title :WriteNdefTag.java * @Package :skyseraph.nfc_demo.tag.write * @ClassName : WriteTask * @Description : TODO * @author : skyseraph00@163.com * @date : 2013-9-13 上午11:38:58 * @version : V1.0 */ static class WriteTask extends AsyncTask<Void, Void, Void> { Activity host = null;
NdefMessage msg = null;
Tag tag = null;
String text = null;
WriteTask(Activity host, NdefMessage msg, Tag tag) { LogUtil.i(MyConstant.TAG, TAG_ASSIST + "into WriteTask AsyncTask"); this.host = host; this.msg = msg; this.tag = tag; }
@Override protected Void doInBackground(Void... arg0) { int size = msg.toByteArray().length;
try { Ndef ndef = Ndef.get(tag);
if (ndef == null) { NdefFormatable formatable = NdefFormatable.get(tag); if (formatable != null) { try { formatable.connect(); try { formatable.format(msg); } catch (Exception e) { text = "Failed to format tag,Tag refused to format"; } } catch (Exception e) { text = "Failed to connect tag,Tag refused to connect"; } finally { formatable.close(); } } else { text = "NDEF is not supported in this Tag"; } } else { ndef.connect();
try { if (!ndef.isWritable()) { text = "Tag is read-only"; } else if (ndef.getMaxSize() < size) { text = "The data cannot written to tag,Message is too big for tag,Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes."; } else { ndef.writeNdefMessage(msg); text = "Message is written tag, message=" + msg; } } catch (Exception e) { text = "Tag refused to connect"; } finally { ndef.close(); } } } catch (Exception e) { text = "Write opreation is failed,General exception: " + e.getMessage(); LogUtil.i(MyConstant.TAG, TAG_ASSIST + "Exception when writing tag,Write opreation is failed" + text); }
return (null); }
@Override protected void onPostExecute(Void unused) { if (text != null) { Toast.makeText(host, text, Toast.LENGTH_SHORT).show(); }
// host.finish(); // after writed, auto finish } }}