@Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); if(intent.hasExtra(NfcAdapter.EXTRA_TAG )) { if(BackgroundTask.isNetworkAvailable(HubMain.this)) { gifImageView.setVisibility(View.INVISIBLE); spinner.setVisibility(View.VISIBLE); } Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); if(parcelables != null && parcelables.length > 0) { readTextfromMessage((NdefMessage)parcelables[0]); } } }
/** * Setup the recognition of nfc tags when the activity is opened (foreground) * * @param activity The corresponding {@link Activity} requesting the foreground dispatch. * @param adapter The {@link NfcAdapter} used for the foreground dispatch. */ public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) { final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass()); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0); IntentFilter[] filters = new IntentFilter[1]; String[][] techList = new String[][]{}; // Filter for nfc tag discovery filters[0] = new IntentFilter(); filters[0].addAction(NfcAdapter.ACTION_TAG_DISCOVERED); filters[0].addCategory(Intent.CATEGORY_DEFAULT); adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList); }
/** * 读取NFC标签文本数据 */ private void readNfcTag(Intent intent) { if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msgs[] = null; int contentSize = 0; if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; contentSize += msgs[i].toByteArray().length; } } try { if (msgs != null) { NdefRecord record = msgs[0].getRecords()[0]; String textRecord = parseTextRecord(record); mTagText += textRecord + "\n\ntext\n" + contentSize + " bytes"; } } catch (Exception e) { } } }
private void resolveIntent(Intent data) { this.setIntent(data); if ((data.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { return; } if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(data.getAction())) { mLastNfcTag = data.getParcelableExtra(NfcAdapter.EXTRA_TAG); long now = new Date().getTime(); if (mContinuousSensorReadingFlag) { startContinuousSensorReadingTimer(); } else if (now - mLastScanTime > 5000) { DataPlotFragment dataPlotFragment = (DataPlotFragment) mSectionsPagerAdapter.getRegisteredFragment(R.integer.viewpager_page_show_scan); if (dataPlotFragment != null) { dataPlotFragment.clearScanData(); } new NfcVReaderTask(this).execute(mLastNfcTag); } } }
/** * Checks to see if the activity's intent ({@link android.app.Activity#getIntent()}) is * an NFC intent that the app recognizes. If it is, then parse the NFC message and set the * activity's intent (using {@link Activity#setIntent(android.content.Intent)}) to something * the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent). */ public static void tryUpdateIntentFromBeam(Activity activity) { Intent originalIntent = activity.getIntent(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(originalIntent.getAction())) { Parcelable[] rawMsgs = originalIntent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0]; // Record 0 contains the MIME type, record 1 is the AAR, if present. // In iosched, AARs are not present. NdefRecord mimeRecord = msg.getRecords()[0]; if (ScheduleContract.makeContentItemType( ScheduleContract.Sessions.CONTENT_TYPE_ID).equals( new String(mimeRecord.getType()))) { // Re-set the activity's intent to one that represents session details. Intent sessionDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(new String(mimeRecord.getPayload()))); activity.setIntent(sessionDetailIntent); } } }
private void handleIntent(final Intent intent) { final String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { final String inputType = intent.getType(); final NdefMessage ndefMessage = (NdefMessage) intent .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)[0]; final byte[] input = Nfc.extractMimePayload(Constants.MIMETYPE_TRANSACTION, ndefMessage); new BinaryInputParser(inputType, input) { @Override protected void handlePaymentIntent(final PaymentIntent paymentIntent) { cannotClassify(inputType); } @Override protected void error(final int messageResId, final Object... messageArgs) { dialog(WalletActivity.this, null, 0, messageResId, messageArgs); } }.parse(); } }
@Override public void onNewIntent(Intent intent) { String action = intent.getAction(); // Log.i("!intent! ", action); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); byte[] id = tag.getId(); String serialNumber = bytesToHex(id); WritableMap idData = Arguments.createMap(); idData.putString("id", serialNumber); sendEvent(this.reactContext, "NFCCardID", idData); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pendingIntent = PendingIntent.getActivity( this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); IntentFilter mifare = new IntentFilter((NfcAdapter.ACTION_TECH_DISCOVERED)); filters = new IntentFilter[] { mifare }; techs = new String[][] { new String[] {NfcA.class.getName() } }; if(adapter==null) { adapter = NfcAdapter.getDefaultAdapter(this); } imageView = (ImageView) findViewById(R.id.imageView); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Animation rotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotation); imageView.startAnimation(rotation); } }); }
@ReactMethod private void registerTagEvent(String alertMessage, Boolean invalidateAfterFirstRead, Callback callback) { Log.d(LOG_TAG, "registerTag"); isForegroundEnabled = true; // capture all mime-based dispatch NDEF IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); try { ndef.addDataType("*/*"); } catch (MalformedMimeTypeException e) { throw new RuntimeException("fail", e); } intentFilters.add(ndef); // capture all rest NDEF, such as uri-based intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)); techLists.add(new String[]{Ndef.class.getName()}); // for those without NDEF, get them as tags intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)); if (isResumed) { enableDisableForegroundDispatch(true); } callback.invoke(); }
@Override public void onCreate(Bundle savedState) { super.onCreate(savedState); mAdapter = NfcAdapter.getDefaultAdapter(this); // Create an NDEF message a URL mMessage = new NdefMessage(NdefRecord.createUri("http://www.android.com")); setContentView(R.layout.foreground_dispatch); mText = (TextView) findViewById(R.id.text); if (mAdapter != null) { mAdapter.setNdefPushMessage(mMessage, this); mText.setText("Tap another Android phone with NFC to push a URL"); } else { mText.setText("This phone is not NFC enabled."); } }
private void processIntent(Intent i) { if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) { Parcelable[] rawMsgs = i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage msg = (NdefMessage) rawMsgs[0]; String url = new String(msg.getRecords()[0].getPayload()); Utils.debugLog(TAG, "Got this URL: " + url); Toast.makeText(this, "Got this URL: " + url, Toast.LENGTH_LONG).show(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setClass(this, ManageReposActivity.class); startActivity(intent); finish(); } }
@TargetApi(16) private void prepareNfcMenuItems(Menu menu) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); MenuItem menuItem = menu.findItem(R.id.menu_enable_nfc); if (nfcAdapter == null) { menuItem.setVisible(false); return; } boolean needsEnableNfcMenuItem; if (Build.VERSION.SDK_INT < 16) { needsEnableNfcMenuItem = !nfcAdapter.isEnabled(); } else { needsEnableNfcMenuItem = !nfcAdapter.isNdefPushEnabled(); } menuItem.setVisible(needsEnableNfcMenuItem); }
@TargetApi(16) public static void setAndroidBeam(Activity activity, String packageName) { if (Build.VERSION.SDK_INT < 16) { return; } PackageManager pm = activity.getPackageManager(); NfcAdapter nfcAdapter = getAdapter(activity); if (nfcAdapter != null) { ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); Uri[] uris = { Uri.parse("file://" + appInfo.publicSourceDir), }; nfcAdapter.setBeamPushUris(uris, activity); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Could not get application info", e); } } }
/** * This activity usually be loaded from the starting screen of the app. * This method handles the start-up of the activity, it does not need to call any other methods * since the activity onNewIntent() calls the intentHandler when a NFC chip is detected. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); documentData = (DocumentData) extras.get(DocumentData.identifier); thisActivity = this; setContentView(R.layout.activity_passport_con); Toolbar appBar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(appBar); Util.setupAppBar(appBar, this); TextView notice = (TextView) findViewById(R.id.notice); progressView = (ImageView) findViewById(R.id.progress_view); mNfcAdapter = NfcAdapter.getDefaultAdapter(this); checkNFCStatus(); notice.setText(R.string.nfc_enabled); }
@Override public void onNewIntent(Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); String[] techList = tag.getTechList(); boolean haveMifareUltralight = false; for (String tech : techList) { if (tech.indexOf("MifareUltralight") >= 0) { haveMifareUltralight = true; break; } } if (!haveMifareUltralight) { Toast.makeText(this, "不支持MifareUltralight数据格式", Toast.LENGTH_SHORT).show(); return; } writeTag(tag); }
@Override public void onNewIntent(Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); String[] techList = tag.getTechList(); boolean haveMifareUltralight = false; for (String tech : techList) { if (tech.indexOf("MifareUltralight") >= 0) { haveMifareUltralight = true; break; } } if (!haveMifareUltralight) { Toast.makeText(this, "不支持MifareUltralight数据格式", Toast.LENGTH_SHORT).show(); return; } String data = readTag(tag); if (data != null) Toast.makeText(this, data, Toast.LENGTH_SHORT).show(); }
public void onNewIntent(Intent intent) { Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{createUriRecord(mUri)}); boolean result = writeTag(ndefMessage, detectedTag); if (result) { Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "写入失败", Toast.LENGTH_SHORT).show(); } }
private void connect(final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { if (getIntent() == null) { // Lost Tag clean(callbackContext, "No tag available."); return; } final Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (tag == null) { clean(callbackContext, "No tag available."); return; } try { Log.i(TAG, "Tag is: " + tag); mifareUltralight.connect(tag); callbackContext.success(); } catch (final Exception e) { clean(callbackContext, e); } } }); }
private void unlock(final CallbackContext callbackContext, final int pin) { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { if (getIntent() == null) { // Lost Tag clean(callbackContext, "No tag available."); return; } final Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (tag == null) { clean(callbackContext, "No tag available."); return; } try { mifareUltralight.unlockWithPin(pin); callbackContext.success(); } catch (final Exception e) { clean(callbackContext, e); } } }); }
/** * Parses the NDEF Message from the intent and prints to the TextView */ void processIntent(Intent intent) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); // only one message sent during the beam NdefMessage msg = (NdefMessage) rawMsgs[0]; // record 0 contains the MIME type, record 1 is the AAR, if present mInfoText.setText(new String(msg.getRecords()[0].getPayload())); }
private void stopNfc() { Log.d(TAG, "stopNfc"); getActivity().runOnUiThread(new Runnable() { public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null) { try { nfcAdapter.disableForegroundDispatch(getActivity()); } catch (IllegalStateException e) { // issue 125 - user exits app with back button while nfc Log.w(TAG, "Illegal State Exception stopping NFC. Assuming application is terminating."); } } } }); }
private void parseMessage() { cordova.getThreadPool().execute(new Runnable() { @Override public void run() { Log.d(TAG, "parseMessage " + getIntent()); Intent intent = getIntent(); String action = intent.getAction(); Log.d(TAG, "action " + action); if (action == null) { return; } Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) { fireTagEvent(tag, "mifareTagDiscovered"); } setIntent(new Intent()); } }); }
/** * If the device has NFC, construct a BeamCallback and pass it to Android. * * @param activity Activity that is sending out beam messages. * @param provider Provider that returns the URL that should be shared. */ public static void registerForBeam(final Activity activity, final BeamProvider provider) { final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (nfcAdapter == null) return; if (ApiCompatibilityUtils.checkPermission( activity, Manifest.permission.NFC, Process.myPid(), Process.myUid()) == PackageManager.PERMISSION_DENIED) { return; } try { final BeamCallback beamCallback = new BeamCallback(activity, provider); nfcAdapter.setNdefPushMessageCallback(beamCallback, activity); nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity); } catch (IllegalStateException e) { Log.w("BeamController", "NFC registration failure. Can't retry, giving up."); } }
private void nfcInit(){ TextView notice= (TextView) findViewById(R.id.nfc_notice); // 监听扫描NFC IntentFilter ifilters=new IntentFilter(); ifilters.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED); //NDEF nfcAdapter=NfcAdapter.getDefaultAdapter(this); pi=PendingIntent.getActivity(this,0,new Intent(this,getClass()),0); if(nfcAdapter==null){ NFCSupport=false; Toast.makeText(this,"Device dose not support NFC!",Toast.LENGTH_LONG).show(); notice.setText("Device dose not support NFC!"); } else if(nfcAdapter!=null&&!nfcAdapter.isEnabled()){ NFCSupport=false; Toast.makeText(this,"Please turn on NFC in your setting.",Toast.LENGTH_LONG).show(); notice.setText("Please turn on NFC in your setting."); } else{ NFCSupport=true; } }
private String readNFCTag(Intent intent){ String response=null; if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())){ //从标签读取数据 Parcelable[] nfcMsgs=intent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES ); NdefMessage msgs[]=null; int contentSize=0; if(nfcMsgs!=null){ msgs=new NdefMessage[nfcMsgs.length]; // 标签可能存储多个NdefMessage对象,一般情况下只有一个 for(int i=0;i<nfcMsgs.length;i++){ // 转换为NdefMessage对象 msgs[i]= (NdefMessage) nfcMsgs[i]; // 计算数据的总长度 contentSize+=msgs[i].toByteArray().length; } } try{ if(msgs!=null){ // 只读第一个信息 NdefRecord record=msgs[0].getRecords()[0]; response=parseTextRecord(record); System.out.println(response); } } catch (Exception e){ Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show(); } } return response; }
/** * Sets this activity's Android Beam message to one representing the given session. */ public static void setBeamSessionUri(Activity activity, Uri sessionUri) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (nfcAdapter == null) { // No NFC :-( return; } nfcAdapter.setNdefPushMessage(new NdefMessage( new NdefRecord[]{ new NdefRecord(NdefRecord.TNF_MIME_MEDIA, ScheduleContract.makeContentItemType( ScheduleContract.Sessions.CONTENT_TYPE_ID).getBytes(), new byte[0], sessionUri.toString().getBytes()) }), activity); }
private void startNfc() { createPendingIntent(); // onResume can call startNfc before execute getActivity().runOnUiThread(new Runnable() { public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter != null && !getActivity().isFinishing()) { try { nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists()); if (p2pMessage != null) { nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); } } catch (IllegalStateException e) { // issue 110 - user exits app with home button while nfc is initializing Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating."); } } } }); }
private void startNdefPush(final CallbackContext callbackContext) { getActivity().runOnUiThread(new Runnable() { public void run() { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if (nfcAdapter == null) { callbackContext.error(STATUS_NO_NFC); } else if (!nfcAdapter.isNdefPushEnabled()) { callbackContext.error(STATUS_NDEF_PUSH_DISABLED); } else { nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity()); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); shareTagCallback = callbackContext; callbackContext.sendPluginResult(result); } } }); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this); Intent intent = getIntent(); String action = intent.getAction(); if (action != null) { if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) { if (nfcAdapter != null && nfcAdapter.isEnabled()) { if (((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name()) != null) { ((NfcShield) ((OneSheeldApplication) getApplication()).getRunningShields().get(UIShield.NFC_SHIELD.name())).handleIntent(intent); } } else { Toast.makeText(getApplicationContext(), R.string.nfc_nfc_disabled_toast, Toast.LENGTH_SHORT).show(); } } else { startActivity(new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); } } else startActivity(new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); } finish(); }
public void registerNFCListener(boolean isToastable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) { NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (nfcAdapter != null && nfcAdapter.isEnabled()) { setupForegroundDispatch(); selectionAction.onSuccess(); } else { if(nfcAdapter == null){ if (isToastable) { activity.showToast(R.string.nfc_device_doesnt_support_nfc); } } else { showSettingsDialogIfNfcIsNotEnabled(); } selectionAction.onFailure(); } } else { if (isToastable) activity.showToast(R.string.nfc_device_doesnt_support_nfc); selectionAction.onFailure(); } }
/** * To be executed on onNewIntent of activity * @param intent */ public void onActivityNewIntent(Intent intent) { // TODO Check if the following line has any use // activity.setIntent(intent); if (textToWrite == null) readTagFromIntent(intent); else { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); try { writeTag(activity, tag, textToWrite); onTagWriteListener.onTagWritten(); } catch (NFCWriteException exception) { onTagWriteErrorListener.onTagWriteError(exception); } finally { textToWrite = null; } } }
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); cinemas = DBHelper.getInstance(getContext()).getCinemas(); watcher = new Gson().fromJson(getArguments().getString("watcher"), Watcher.class); nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); if(nfcAdapter != null) { nfcAdapter.setNdefPushMessageCallback(new NfcAdapter.CreateNdefMessageCallback() { @Override public NdefMessage createNdefMessage(NfcEvent nfcEvent) { return new NdefMessage( new NdefRecord[] { NdefRecord.createUri(BuildConfig.SERVER_BASE_URL + "w/" + watcher.getID()), NdefRecord.createApplicationRecord(BuildConfig.APPLICATION_ID) } ); } }, getActivity()); } }
private static void sendNfcState(ResultReceiver receiver) { if (mContext == null || receiver == null) return; int nfcState = NFC_STATE_UNKNOWN; try { NfcAdapter adapter = NfcAdapter.getDefaultAdapter(mContext); if (adapter != null) { nfcState = (Integer) XposedHelpers.callMethod(adapter, "getAdapterState"); } } catch (Throwable t) { XposedBridge.log(t); } finally { Bundle b = new Bundle(); b.putInt("nfcState", nfcState); receiver.send(0, b); } }
private void handleIntent(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { String type = intent.getType(); if (type.equals("application/vnd.bluetooth.ep.oob")) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); new NdefReaderTask().execute(tag); } else { Log.d(TAG, "Wrong mime type: " + type); } } }
private void resolveIntent(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage[] msgs; if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; } } else { // Unknown tag type //byte[] empty = new byte[0]; //byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); showTagId(tag); //byte[] payload = dumpTagData(tag).getBytes(); //NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload); //NdefMessage msg = new NdefMessage(new NdefRecord[] { record }); //msgs = new NdefMessage[] { msg }; } // Setup the views //buildTagViews(msgs); } }
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) { Toast.makeText(this, "NfcIntent!", Toast.LENGTH_SHORT).show(); Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); NdefMessage ndefMessage = createNdefMessage("My string content!"); writeNdefMessage(tag, ndefMessage); } }
void resolveIntent(Intent intent) { Log.i("test", "start method"); // 1) Parse the intent and get the action that triggered this intent String action = intent.getAction(); // 2) Check if it was triggered by a tag discovered interruption. if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) { Log.i("test", "in if"); // 3) Get an instance of the TAG from the NfcAdapter Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); byte[] id = tagFromIntent.getId(); try { lastDetectUid = getHexString(id); // 讀到tag即自動填寫uid欄位 if(dialogRecordUid != null && dialogRecordUid.isShown()){ dialogRecordUid.setText(lastDetectUid); }else{ ShowAddNewDialog(); } } catch (Exception e1) { e1.printStackTrace(); } }// End of method else { Log.i("Error", action); } Log.i("test", "end method"); }
public void onNewIntent (Intent intent) { Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); byte[] id = tag.getId(); ByteBuffer wrapped = ByteBuffer.wrap(id); wrapped.order(ByteOrder.LITTLE_ENDIAN); int signedInt = wrapped.getInt(); long number = signedInt & 0xfffffff1; Evt(number); }