본문 바로가기

안드로이드

android nfc mime type 이용하기

반응형

mime type을 이용하여 nfc 실행시 프로그램 선택없이 자신의 앱만 실행시키는 방법입니다.


1.nfc를 찍었을때 자신의 앱을 바로  실행시키게 할려면 nfc태그를 쓸때 mime type을 같이 write 시켜줘야 합니다. 


2.아래 링크에서 앱을 다운받아서 앱을 구분 할 수 있는 값을 nfc태그를 쓸때 같이 써줍니다(소스도 있으니 참고하시기 바랍니다)

 -마켓링크 : https://play.google.com/store/apps/details?id=nl.paulus.nfctagwriter

 - 소스 : https://github.com/balloob/Android-NFC-Tag-Writer



3. 앱 구분값 : application/com.appmaker.nfc ,   태그값 : test   로 write 했습니다.






- 이 태그를 읽는 소스입니다.


package com.appmaker.nfcread;


import java.io.UnsupportedEncodingException;

import java.util.ArrayList;


import android.app.Activity;

import android.app.PendingIntent;

import android.content.Intent;

import android.content.IntentFilter;

import android.content.IntentFilter.MalformedMimeTypeException;

import android.nfc.NdefMessage;

import android.nfc.NdefRecord;

import android.nfc.NfcAdapter;

import android.nfc.Tag;

import android.nfc.tech.Ndef;

import android.os.AsyncTask;

import android.os.Bundle;

import android.provider.Settings;

import android.util.Log;

import android.widget.Toast;


public class NfcRead extends Activity {

private NfcAdapter mNfcAdapter;

public static final String MIME_TEXT_PLAIN = "application/com.appmaker.nfc"; //앱구분값을 써줍니다



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);


mNfcAdapter = NfcAdapter.getDefaultAdapter(this);


if (mNfcAdapter == null) {

Toast.makeText(this, "NFC를 지원하지 않는 기기입니다.", Toast.LENGTH_LONG)

.show();

return;

}


if (!mNfcAdapter.isEnabled()) {

Intent setnfc = new Intent(Settings.ACTION_WIRELESS_SETTINGS);

startActivity(setnfc);

} else {

handleIntent(getIntent());

}


}


@Override

protected void onResume() {

super.onResume();

setupForegroundDispatch(this, mNfcAdapter);

}


private void handleIntent(Intent intent) {

String action = intent.getAction();


if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {


String type = intent.getType();

if (MIME_TEXT_PLAIN.equals(type)) {

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);


new NdefReaderTask().execute(tag);


} else {

}

} else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {


Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

String[] techList = tag.getTechList();

String searchedTech = Ndef.class.getName();


for (String tech : techList) {

if (searchedTech.equals(tech)) {

new NdefReaderTask().execute(tag);

break;

}

}

}

}


@Override

protected void onPause() {

stopForegroundDispatch(this, mNfcAdapter);


super.onPause();

}


@Override

protected void onNewIntent(Intent intent) {

handleIntent(intent);

}


public static void setupForegroundDispatch(final Activity activity,

NfcAdapter adapter) {

final Intent intent = new Intent(activity.getApplicationContext(),

activity.getClass());

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);


final PendingIntent pendingIntent = PendingIntent.getActivity(

activity.getApplicationContext(), 0, intent, 0);


IntentFilter[] filters = new IntentFilter[1];

String[][] techList = new String[][] {};


filters[0] = new IntentFilter();

filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);

filters[0].addCategory(Intent.CATEGORY_DEFAULT);

try {

filters[0].addDataType(MIME_TEXT_PLAIN);

} catch (MalformedMimeTypeException e) {

throw new RuntimeException("Check your mime type.");

}


adapter.enableForegroundDispatch(activity, pendingIntent, filters,

techList);

}


public static void stopForegroundDispatch(final Activity activity,

NfcAdapter adapter) {

adapter.disableForegroundDispatch(activity);

}


private class NdefReaderTask extends AsyncTask<Tag, Void, String> {


@Override

protected String doInBackground(Tag... params) {

Tag tag = params[0];

Ndef ndef = Ndef.get(tag);

if (ndef == null) {

// NDEF is not supported by this Tag.

return null;

}


NdefMessage ndefMessage = ndef.getCachedNdefMessage();


NdefRecord[] records = ndefMessage.getRecords();


for (NdefRecord ndefRecord : records) {

try {

return readText(ndefRecord);

} catch (UnsupportedEncodingException e) {

Log.e("myLog", "Unsupported Encoding", e);

}


// if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN

// && Arrays.equals(ndefRecord.getType(),

// NdefRecord.RTD_TEXT)) {

// try {

// return readText(ndefRecord);

// } catch (UnsupportedEncodingException e) {

// Log.e("myLog", "Unsupported Encoding", e);

// }

// }

}


return null;

}


private String readText(NdefRecord record)

throws UnsupportedEncodingException {


byte[] payload = record.getPayload();


String value = new String(payload, "UTF-8");


return value;

}


@Override

protected void onPostExecute(String result) {


if (result != null) {

Toast.makeText(NfcRead.this, result, Toast.LENGTH_SHORT).show();

}

}


}


}




AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.appmaker.nfcread"

    android:versionCode="1"

    android:versionName="1.0" >


    <uses-sdk

        android:minSdkVersion="10"

        android:targetSdkVersion="19" />


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

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


    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.appmaker.nfcread.MainActivity"

            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.appmaker.nfcread.NfcRead"

            android:launchMode="singleInstance" >

            <intent-filter>

                <action android:name="android.nfc.action.NDEF_DISCOVERED" />


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


                <data android:mimeType="application/com.appmaker.nfc" /> 

<!-- 앱 구분값을 mimeType 에 써줍니다 -->

            </intent-filter>

            <intent-filter>

                <action android:name="android.nfc.action.TECH_DISCOVERED" />

            </intent-filter>


            <meta-data

                android:name="android.nfc.action.TECH_DISCOVERED"

                android:resource="@xml/nfc_tech_filter" />

        </activity>

    </application>


</manifest>




nfc_tech_filter.xml


<?xml version="1.0" encoding="utf-8"?>

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

<tech-list>


<tech>android.nfc.tech.NfcA</tech>

<tech>android.nfc.tech.Ndef</tech>

<tech>android.nfc.tech.MifareUltralight</tech>

</tech-list>

</resources>



nfc 태그종류에 따라 nfc_tech_filter.xml 를 조금 바꿔주셔야 할 경우도 있습니다.

다들 성공하시길 빕니다!

도움이 되셨다면 광고한번씩 클릭해주세요!





반응형