NFC意图过滤器 - 发送消息非主要活动

时间:2012-11-04 20:33:52

标签: android nfc

我确信这很简单,但我无法弄清楚。我所要做的就是通过NFC发送消息。如果我将代码发送到主要活动,我的代码完美无缺,但我不知道如何将其发送到其他活动。我查看了Android Developer页面上的NFC和Intent Filter文章,但我仍然不确定如何做到这一点。我正在尝试将其发送到NFC活动,我将在下面发布我的清单和NFC课程。

清单:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.justbaumdev.tagsense"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.NFC" />

    <uses-feature android:name="android.hardware.nfc" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo" >
        <activity
            android:name=".TagSense"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.justbaumdev.tagsense.NFC" android:exported="false">
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />

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

                <data android:mimeType="application/com.justbaumdev.tagsense" />
            </intent-filter>
        </activity>
    </application>

</manifest>

NFC等级:

package com.justbaumdev.tagsense;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.widget.Toast;

public class NFC extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
    private NfcAdapter mNfcAdapter;
    private static final int MESSAGE_SENT = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nfc);
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this); // Check for available NFC Adapter
        if (mNfcAdapter == null) 
        {
            Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        else 
        {
            mNfcAdapter.setNdefPushMessageCallback(this, this); // Register callback to set NDEF message
            mNfcAdapter.setOnNdefPushCompleteCallback(this, this); // Register callback to listen for message-sent success
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        // Check to see that the Activity started due to an Android Beam
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }


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


    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        String mac = wm.getConnectionInfo().getMacAddress();
        String newMac = mac.substring(0, 2);
        mac = mac.substring(2);
        int hex = Integer.parseInt(newMac, 16) + 0x2;
        newMac = Integer.toHexString(hex);
        String text = newMac + mac;

        NdefMessage msg = new NdefMessage(NdefRecord.createMime(
                "application/com.justbaumdev.tagsense", text.getBytes()));
        return msg;
    }


    /**
     * Implementation for the OnNdefPushCompleteCallback interface
     */
    @Override
    public void onNdefPushComplete(NfcEvent arg0) {
        // A handler is needed to send messages to the activity when this
        // callback occurs, because it happens from a binder thread
        mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
    }


    /** This handler receives a message from onNdefPushComplete */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_SENT:
                Toast.makeText(getApplicationContext(), "Message sent!", Toast.LENGTH_LONG).show();
                break;
            }
        }
    };


    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    //TODO Currently overwrites any previously saved mac addresses.  Get FB ID as value.  Auto end activity.
    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
        //textView.setText(new String(msg.getRecords()[0].getPayload()));
        String payload = new String(msg.getRecords()[0].getPayload());
        Toast.makeText(this, new String(msg.getRecords()[0].getPayload()), Toast.LENGTH_LONG).show();

        SharedPreferences appData = getSharedPreferences("appData", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = appData.edit();
        String addresses = appData.getString("mac_address", null);
        if(addresses==null)
        {
            JSONArray addressArray = new JSONArray();
            addressArray.put(payload);
            addresses = addressArray.toString();
        }
        else
        {
            try {
                if(!addresses.contains(payload))
                {
                    JSONArray addressArray = new JSONArray(addresses);
                    addressArray.put(payload);
                    addresses = addressArray.toString();
                }
            } catch (JSONException e) {
                Toast.makeText(this, "Error adding new friend. Please try again.", Toast.LENGTH_SHORT).show();
            }
        }
        editor.putString("mac_address", addresses);
        editor.commit();
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

删除属性android:exported="false"。另请参阅https://stackoverflow.com/a/12719621/1202968