用户单击按钮后读取nfc芯片

时间:2014-04-09 13:32:15

标签: android nfc

按下按钮后可以从nfc芯片开始读取。按下按钮后,应该有一条消息,例如“请将你的nfc芯片靠近设备......”。我只看到教程,其中展示了如何在将nfc芯片保存到设备时启动应用程序(onNewIntent)。

第二个问题。如果应用程序已经运行并且我的设备旁边有nfc芯片怎么办?是强迫销毁然后再次发射?

谢谢!

1 个答案:

答案 0 :(得分:1)

关于问题的第一部分,您可以在活动中使用一个标志来指示应用程序的状态(准备写入/消息正在显示,未准备好写入/消息未显示)。你可以找到一个简单的例子here

private static final int DIALOG_WRITE = 1;
private boolean mWrite = false;  // write state

public void onCreate(Bundle savedInstanceState) {

    [...]

    // Set action for "Write to tag..." button:
    mMyWriteButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Switch to write mode:
            mWrite = true;

            // Show a dialog when we are ready to write:
            showDialog(DIALOG_WRITE);
        }
    });

    [...]
}

protected Dialog onCreateDialog(int id, Bundle args) {
    switch (id) {
        case DIALOG_WRITE:
            // A dialog that we show when we are ready to write to a tag:
            return new AlertDialog.Builder(this)
                    .setTitle("Write to tag...")
                    .setMessage("Touch tag to start writing.")
                    .setCancelable(true)
                    .setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int arg) {
                            d.cancel();
                        }
                    })
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        public void onCancel(DialogInterface d) {
                            mWrite = false;
                        }
                    }).create();
    }

    return null;
}

// You would call this method from onCreate/onStart/onResume/onNewIntent
// or from whereever you want to process an incoming intent
private void resolveIntent(Intent data, boolean foregroundDispatch) {
    String action = data.getAction();

    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        // The reference to the tag that invoked us is passed as a parameter (intent extra EXTRA_TAG)
        Tag tag = data.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        if (mWrite) {
            // We want to write
            mWrite = false;

            // TODO: write to tag
        } else {
            // not in write-mode

            // TODO: read tag or do nothing
        }
    }
}

关于问题的第二部分,当您希望在活动已经在前台时接收NFC标签发现事件时,您应该注册NFC前台调度系统。见Advanced NFC: Using the NFC Foreground Dispatch System。没有必要销毁和重新创建您的活动。