NFC意图过滤器 - 发送邮件非主要活动 [英] NFC Intent Filter - Sending Message Non-Main Activity

查看:276
本文介绍了NFC意图过滤器 - 发送邮件非主要活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这是简单的,但我不能弄明白。所有我试图做的是通过NFC发送消息。在code我有很好的工作,如果我把它发送到主要活动,但我不知道如何将它发送到不同的活动。我已经看过了两个NFC和意图过滤文章对Android开发者页面,但现在还不能确定究竟是如何做到这一点。我试图把它发送到NFC活动,我会后下我的清单和NFC类。

I am sure this is simple but I cannot figure it out. All I am trying to do is send a message via NFC. The code I have work perfectly if I am sending it to the main activity, but I don't know how to send it to a different activity. I have looked over both the NFC and Intent Filter articles on the Android Developer pages but am still not sure exactly how to do this. I am trying to send it to a NFC activity, I will post my manifest and NFC class below.

清单:

<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();
    }
}

感谢您的帮助。

推荐答案

删除属性的android:出口=FALSE。参见<一个href=\"http://stackoverflow.com/a/12719621/1202968\">http://stackoverflow.com/a/12719621/1202968

这篇关于NFC意图过滤器 - 发送邮件非主要活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆