Java 扫描NFC标签后如何启动应用程序和调用方法?
我是NFC的新手 我正试图通过扫描NFC标签打开我的应用程序,然后在它打开之后 我希望应用程序仅在通过NFC打开应用程序时调用方法。 我知道如何从标签中读写,并通过扫描打开应用程序。但在应用程序打开后,如何调用方法? 我使用的是来自互联网的开源软件,它对我来说非常有用。如果你能给我正确的操作方法,我会很高兴的。 代码如下: 主要内容: NFC管理员:Java 扫描NFC标签后如何启动应用程序和调用方法?,java,android,nfc,Java,Android,Nfc,我是NFC的新手 我正试图通过扫描NFC标签打开我的应用程序,然后在它打开之后 我希望应用程序仅在通过NFC打开应用程序时调用方法。 我知道如何从标签中读写,并通过扫描打开应用程序。但在应用程序打开后,如何调用方法? 我使用的是来自互联网的开源软件,它对我来说非常有用。如果你能给我正确的操作方法,我会很高兴的。 代码如下: 主要内容: NFC管理员: public class PillowNfcManager { NfcAdapter nfcAdapter; A
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);
}
任何一个?您必须根据正在侦听的标记类型(由清单中的意图过滤器定义)检查启动活动的意图操作。 例如:
Intent i = getIntent();
if(i.getAction() == NfcAdapter.ACTION_TAG_DISCOVERED)
{
//runYourMethod();
}
使用您的标记类型:
您能给我提供更多信息吗?我已经读过android开发者的书了,但还是不明白。
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();
}
Intent i = getIntent();
if(i.getAction() == NfcAdapter.ACTION_TAG_DISCOVERED)
{
//runYourMethod();
}