2016-04-12 2 views
-1

Я новичок в NFC , и я пытаюсь открыть приложение, сканируя тег NFC и после его открытия. Я хочу, чтобы приложение вызывало метод, только если приложение открылось через NFC. Я знаю, как писать и читать из тега и открывать приложение путем сканирования. Но как я могу вызвать метод после открытия приложения? Я использовал открытый исходный код из Интернета, и он работает для меня довольно хорошо. Я был бы счастлив, если бы вы задали мне, как это сделать правильно. Вот код: Main:Как запустить приложение и метод вызова после сканирования тега NFC?

public class PillowNfcSample extends ActionBarActivity { 
    PillowNfcManager nfcManager; 
    WriteTagHelper writeHelper; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_sample); 

     nfcManager = new PillowNfcManager(this); 
     nfcManager.onActivityCreate(); 

     nfcManager.setOnTagReadListener(new PillowNfcManager.TagReadListener() { 
      @Override 
      public void onTagRead(String tagRead) { 
       Toast.makeText(PillowNfcSample.this, "tag read:"+tagRead, Toast.LENGTH_LONG).show(); 
      } 
     }); 

     writeHelper= new WriteTagHelper(this, nfcManager); 
     nfcManager.setOnTagWriteErrorListener(writeHelper); 
     nfcManager.setOnTagWriteListener(writeHelper); 

     Button writeButton = (Button) findViewById(R.id.write_button); 
     writeButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       String text = new Date().toString(); 
       writeHelper.writeText(text); 
      } 
     }); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     nfcManager.onActivityResume(); 
    } 

    @Override 
    protected void onPause() { 
     nfcManager.onActivityPause(); 
     super.onPause(); 
    } 

    @Override 
    public void onNewIntent(Intent intent){ 
     nfcManager.onActivityNewIntent(intent); 
    } 

} 

NfcManager:

public class PillowNfcManager { 
     NfcAdapter nfcAdapter; 
     Activity activity; 
     PendingIntent pendingIntent; 

     TagReadListener onTagReadListener; 
     TagWriteListener onTagWriteListener; 
     TagWriteErrorListener onTagWriteErrorListener; 

     String writeText = null; 


     public PillowNfcManager(Activity activity) { 
      this.activity = activity; 
     } 

     /** 
     * Sets the listener to read events 
     */ 
     public void setOnTagReadListener(TagReadListener onTagReadListener) { 
      this.onTagReadListener = onTagReadListener; 
     } 

     /** 
     * Sets the listener to write events 
     */ 
     public void setOnTagWriteListener(TagWriteListener onTagWriteListener) { 
      this.onTagWriteListener = onTagWriteListener; 
     } 

     /** 
     * Sets the listener to write error events 
     */ 
     public void setOnTagWriteErrorListener(TagWriteErrorListener onTagWriteErrorListener) { 
      this.onTagWriteErrorListener = onTagWriteErrorListener; 
     } 

     /** 
     * Indicates that we want to write the given text to the next tag detected 
     */ 
     public void writeText(String writeText) { 
      this.writeText = writeText; 
     } 

     /** 
     * Stops a writeText operation 
     */ 
     public void undoWriteText() { 
      this.writeText = null; 
     } 


     /** 
     * To be executed on OnCreate of the activity 
     * @return true if the device has nfc capabilities 
     */ 
     public boolean onActivityCreate() { 
      nfcAdapter = NfcAdapter.getDefaultAdapter(activity); 
      pendingIntent = PendingIntent.getActivity(activity, 0, 
        new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 
      return nfcAdapter!=null; 
     } 

     /** 
     * To be executed on onResume of the activity 
     */ 
     public void onActivityResume() { 
      if (nfcAdapter != null) { 
       if (!nfcAdapter.isEnabled()) { 
        //TODO indicate that wireless should be opened 
       } 
       nfcAdapter.enableForegroundDispatch(activity, pendingIntent, null, null); 
      } 
     } 

     /** 
     * To be executed on onPause of the activity 
     */ 
     public void onActivityPause() { 
      if (nfcAdapter != null) { 
       nfcAdapter.disableForegroundDispatch(activity); 
      } 
     } 

     /** 
     * 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 (writeText == null) 
       readTagFromIntent(intent); 
      else { 
       Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
       try { 
        writeTag(activity, tag, writeText); 
        onTagWriteListener.onTagWritten(); 
       } catch (NFCWriteException exception) { 
        onTagWriteErrorListener.onTagWriteError(exception); 
       } finally { 
        writeText = null; 
       } 
      } 
     } 

     /** 
     * Reads a tag for a given intent and notifies listeners 
     * @param intent 
     */ 
     private void readTagFromIntent(Intent intent) { 
      String action = intent.getAction(); 
      if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { 
       Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
       Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 
       if (rawMsgs != null) { 
        NdefRecord[] records = ((NdefMessage) rawMsgs[0]).getRecords(); 
        String text = ndefRecordToString(records[0]); 
        onTagReadListener.onTagRead(text); 
       } 
      } 
     } 

     public String ndefRecordToString(NdefRecord record) { 
      byte[] payload = record.getPayload(); 
      return new String(payload); 
     } 


     public void clearTag(Tag tag){ 
      Ndef ndefTag = Ndef.get(tag); 
      try { 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 
        ndefTag.writeNdefMessage(new NdefMessage(new NdefRecord(NdefRecord.TNF_EMPTY, null, null, null))); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } catch (FormatException e) { 
       e.printStackTrace(); 
      } 
     } 

     /** 
     * Writes a text to a tag 
     * @param context 
     * @param tag 
     * @param data 
     * @throws NFCWriteException 
     */ 
     @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 
     protected void writeTag(Context context, Tag tag, String data) throws NFCWriteException { 
      // Record with actual data we care about 
      NdefRecord relayRecord = new NdefRecord(NdefRecord.TNF_ABSOLUTE_URI, NdefRecord.RTD_URI, null, data.getBytes()); 

      // Complete NDEF message with both records 
      NdefMessage message = new NdefMessage(new NdefRecord[] { 
        relayRecord,NdefRecord.createApplicationRecord("com.mateuyabar.android.pillownfc")}); 

      Ndef ndef = Ndef.get(tag); 
      if (ndef != null) { 
       // If the tag is already formatted, just write the message to it 
       try { 
        ndef.connect(); 
       } catch (IOException e) { 
        throw new NFCWriteException(NFCErrorType.unknownError); 
       } 
       // Make sure the tag is writable 
       if (!ndef.isWritable()) { 
        throw new NFCWriteException(NFCErrorType.ReadOnly); 
       } 

       // Check if there's enough space on the tag for the message 
       int size = message.toByteArray().length; 
       if (ndef.getMaxSize() < size) { 
        throw new NFCWriteException(NFCErrorType.NoEnoughSpace); 
       } 

       try { 
        // Write the data to the tag 
        ndef.writeNdefMessage(message); 
       } catch (TagLostException tle) { 
        throw new NFCWriteException(NFCErrorType.tagLost, tle); 
       } catch (IOException ioe) { 
        throw new NFCWriteException(NFCErrorType.formattingError, ioe);// nfcFormattingErrorTitle 
       } catch (FormatException fe) { 
        throw new NFCWriteException(NFCErrorType.formattingError, fe); 
       } 
      } else { 
       // If the tag is not formatted, format it with the message 
       NdefFormatable format = NdefFormatable.get(tag); 
       if (format != null) { 
        try { 
         format.connect(); 
         format.format(message); 
        } catch (TagLostException tle) { 
         throw new NFCWriteException(NFCErrorType.tagLost, tle); 
        } catch (IOException ioe) { 
         throw new NFCWriteException(NFCErrorType.formattingError, ioe); 
        } catch (FormatException fe) { 
         throw new NFCWriteException(NFCErrorType.formattingError, fe); 
        } 
       } else { 
        throw new NFCWriteException(NFCErrorType.noNdefError); 
       } 
      } 

     } 

     public interface TagReadListener { 
      void onTagRead(String tagRead); 
     } 

     public interface TagWriteListener { 
      void onTagWritten(); 
     } 

     public interface TagWriteErrorListener { 
      void onTagWriteError(NFCWriteException exception); 
     } 

Вспомогательный класс:

public class WriteTagHelper implements PillowNfcManager.TagWriteErrorListener, PillowNfcManager.TagWriteListener{ 
    AlertDialog dialog; 
    PillowNfcManager nfcManager; 
    Context context; 
    int dialogViewId = R.layout.write_nfc_dialog_view; 

    public WriteTagHelper(Context context, PillowNfcManager nfcManager) { 
     this.context = context; 
     this.nfcManager = nfcManager; 
    } 

    /** 
    * Write the given text to a tag. 
    * @param text 
    */ 
    public void writeText(String text){ 
     dialog = createWaitingDialog(); 
     dialog.show(); 
     nfcManager.writeText(text); 
    } 


    @Override 
    public void onTagWritten() { 
     dialog.dismiss(); 
     Toast.makeText(context, R.string.tag_written_toast, Toast.LENGTH_LONG).show();; 
    } 

    @Override 
    public void onTagWriteError(NFCWriteException exception) { 
     dialog.dismiss(); 
     //TODO translate exeptions 
     Toast.makeText(context, exception.getType().toString(), Toast.LENGTH_LONG).show(); 
    } 

    /** 
    * Creates a dialog while waiting for the tag 
    * @return 
    */ 
    public AlertDialog createWaitingDialog(){ 
     LayoutInflater inflater = LayoutInflater.from(context); 
     View view = inflater.inflate(dialogViewId, null, false); 
     ImageView image = new ImageView(context); 
     image.setImageResource(R.drawable.ic_nfc_black_48dp); 
     AlertDialog.Builder builder = new AlertDialog.Builder(context); 
     builder.setTitle(R.string.wait_write_dialog_title) 
     .setView(view) 
     .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       nfcManager.undoWriteText(); 
      } 
     }); 
     return builder.create(); 
    } 

Любой один?

ответ

0

Необходимо проверить действие намерения вашей активности запуска по типу тега, который вы слушаете (определяется фильтром Intent в манифесте). Например:

Intent i = getIntent(); 
if(i.getAction() == NfcAdapter.ACTION_TAG_DISCOVERED) 
{ 
    //runYourMethod(); 
} 

использовать тип тега: http://developer.android.com/reference/android/nfc/NfcAdapter.html

+0

Можете ли вы дать мне более подробную информацию? Я уже прочитал разработчика Android, но все равно не понял. – Anna