阅读NFC标签和后退按钮

时间:2013-01-21 08:06:33

标签: android nfc

我的问题与后退按钮和后台堆有关,我有一个用于读取nfc标签的应用程序,因此我启动了活动A,然后转到活动B,在清单中声明为SingleTop。 我把电话接到标签上然后读取标签,此刻一切正常。

如果按下后退按钮,它会返回到活动B,而不是进入活动A,然后如果我再次按下后退按钮,它将进入活动A.

像这样:

A-&gt; B-&gt;读取标签 - &gt; B-&gt;按下后退按钮 - &gt; B-&gt;按下后退按钮 - &gt; A-&gt;按下后退按钮 - &gt;关闭应用程序。< / p>

我想这样:

A-> B->读取标签 - > B->按下后退按钮 - &gt; A-&gt;按下后退按钮 - &gt;关闭应用程序。

我只想要一个B实例 我尝试过单一任务,但问题是我点击了应用程序图标,然后启动了活动b,但保留了阅读标签的意图。

public class B extends Activity {
private static final String KINVEY_KEY = YOUR_APP_KEY;
private static final String KINVEY_SECRET_KEY = 'YOUR_APP_SECRET_KEY';

private KCSClient kinveyClient;
private NfcAdapter mNfcAdapter;

private Button mEnableWriteButton;
private EditText mTextField;
private ProgressBar mProgressBar;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tags);

    mTextField = (EditText) findViewById(R.id.text_field);

    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    mProgressBar.setVisibility(View.GONE);

    mEnableWriteButton = (Button) findViewById(R.id.enable_write_button);
    mEnableWriteButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            setTagWriteReady(!isWriteReady);
            mProgressBar.setVisibility(isWriteReady ? View.VISIBLE : View.GONE);
        }
    });

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter == null) {
        Toast.makeText(this, 'Sorry, NFC is not available on this device', Toast.LENGTH_SHORT).show();
        finish();
    }

    // Initialize Kinvey
    KinveySettings settings = new KinveySettings(KINVEY_KEY, KINVEY_SECRET_KEY);
    kinveyClient = KCSClient.getInstance(this.getApplicationContext(), settings);
}

private boolean isWriteReady = false;

public void setTagWriteReady(boolean isWriteReady) {
    this.isWriteReady = isWriteReady;
    if (isWriteReady) {
        IntentFilter[] writeTagFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) };
        mNfcAdapter.enableForegroundDispatch(TagsActivity.this, NfcUtils.getPendingIntent(TagsActivity.this),
                writeTagFilters, null);
    } else {
        // Disable dispatch if not writing tags
        mNfcAdapter.disableForegroundDispatch(TagsActivity.this);
    }
    mProgressBar.setVisibility(isWriteReady ? View.VISIBLE : View.GONE);
}

@Override
public void onNewIntent(Intent intent) {
    // onResume gets called after this to handle the intent
    setIntent(intent);
}

@Override
public void onResume() {
    super.onResume();
    if (isWriteReady && NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {
        processWriteIntent(getIntent());
    } else if (!isWriteReady
            && (NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED
                    .equals(getIntent().getAction()))) {
        processReadIntent(getIntent());
    }
}

private static final String MIME_TYPE = 'application/com.tapped.nfc.tag';


public void processWriteIntent(Intent intent) {
    if (isWriteReady && NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {

        Tag detectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);

        String tagWriteMessage = mTextField.getText().toString();
        byte[] payload = new String(tagWriteMessage).getBytes();

        if (detectedTag != null && NfcUtils.writeTag(
                NfcUtils.createMessage(MIME_TYPE, payload), detectedTag)) {

            Toast.makeText(this, "Wrote '" + tagWriteMessage + "' to a tag!", 
                    Toast.LENGTH_LONG).show();
            setTagWriteReady(false);
        } else {
            Toast.makeText(this, "Write failed. Please try again.", Toast.LENGTH_LONG).show();
        }
    }
}

public void processReadIntent(Intent intent) {
    List<NdefMessage> intentMessages = NfcUtils.getMessagesFromIntent(intent);
    List<String> payloadStrings = new ArrayList<String>(intentMessages.size());

    for (NdefMessage message : intentMessages) {
        for (NdefRecord record : message.getRecords()) {
            byte[] payload = record.getPayload();
            String payloadString = new String(payload);

            if (!TextUtils.isEmpty(payloadString))
                payloadStrings.add(payloadString);
        }
    }

    if (!payloadStrings.isEmpty()) {
        String content =  TextUtils.join(",", payloadStrings);
        Toast.makeText(TagsActivity.this, "Read from tag: " + content,
                Toast.LENGTH_LONG).show();
        saveTag(content);
    }
}

private void saveTag(String tagMessage){
    TagReadEntity tag = new TagReadEntity(UUID.randomUUID().toString(), 
            tagMessage, System.currentTimeMillis());

    kinveyClient.mappeddata("tags").save(tag, new ScalarCallback<TagReadEntity>() {

        @Override
        public void onSuccess(TagReadEntity tag) {
            Log.i("NFC Demo", "Saved tag!");
        }

        @Override
        public void onFailure(Throwable e) {
            Log.e("NFC Demo", "Error saving tag", e);
        }
    });
}
}

和清单:

<activity
        android:name=".TagsActivity"
        android:label="@string/title_activity_tags"
        android:launchMode="singleTop"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="application/com.tapped.nfc.tag" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.TAG_DISCOVERED" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:mimeType="application/com.tapped.nfc.tag" />
        </intent-filter>
    </activity>  

1 个答案:

答案 0 :(得分:0)

我已将任务宣布为单项任务,现在似乎正常工作。

android:launchMode="singleTask"

我已尝试过标准,每次我读取nfc标签,都会创建一个新活动,如果读取10个标签,我需要按下后退按钮9次。 在我尝试了singleTop之后,现在我从A到B,然后无论我多少次阅读标签,只有2个B的实例,所以我需要按回一次去活动B,然后再回到关闭应用程序。