我是新的开发者android。如何在onCreate主要活动中使用此代码当我触摸NFC标签读取数据时。我使用流动代码读取标签,如何更改它来解决问题?
in manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.Ultralight"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.NFC" />
<uses-sdk android:minSdkVersion="10" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
<activity android:name="MainView"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</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/tech_filter"/>
</activity>
</application>
</manifest>
答案 0 :(得分:3)
如果您希望应用仅在应用启动时对标记执行操作,则需要在OnCreate中设置一个意图过滤器并对其进行操作。这样的事情。
更新:添加了代码。
NfcAdapter mAdapter;
private PendingIntent mPendingIntent;
private IntentFilter[] mFilters;
private String[][] mTechLists;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fbintenthandler);
mAdapter = NfcAdapter.getDefaultAdapter(this);
mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ntech2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter ntech3 = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
mFilters = new IntentFilter[] {
ntech3, ntech2,
};
mTechLists = new String[][] { new String[] {
NfcA.class.getName(),
Ndef.class.getName() } };
Intent intent = getIntent();
resolveIntent (intent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
resolveIntent(intent);
}
private void resolveIntent (Intent intent)
{
String action = intent.getAction();
if ((NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) ||
(NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)))
{
Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Parcelable[] rawMsgs = intent
.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
extractMessage(msg);
}
}
private void extractMessage(NdefMessage msg) {
byte[] array = null;
array = msg.getRecords()[0].getPayload();
String displaystring = convert (array);
TextView tv = (TextView) findViewById(R.id.txt_DisplayData);
tv.setText(displaystring);
}
String convert(byte[] data) {
StringBuilder sb = new StringBuilder(data.length);
for (int i = 0; i < data.length; ++ i) {
if (data[i] < 0) throw new IllegalArgumentException();
sb.append((char) data[i]);
}
return sb.toString();
}