我對這個解決方案是通過NFC意向啓動一個無頭(不可見)的活動,並使用一個共享的偏好(由通過UI開關設定主要活動)來確定是否啓動主要活動。
AndroidManifest.xml
:
<activity android:name="com.mypackage.NFCLaunchActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar">
<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>
res/nfc_tech_filter.xml
:
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
</tech-list>
</resources>
MainActivity.java
:
public static String SETTINGS_NAME = "settings";
public static String shouldLaunchByNFC = "launchWithNfc";
// Call on changing UI state
protected void setShouldLaunchByNFC(boolean enableLaunch) {
setSettingBoolean(this, shouldLaunchByNFC, enableLaunch);
}
// Call to set initial UI state
protected boolean getShouldLaunchByNFC() {
return getSettingBoolean(this, shouldLaunchByNFC, true);
}
public static void setSettingBoolean(Activity activity, String name, boolean value){
SharedPreferences settings = activity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(name, value);
editor.commit();
}
public static boolean getSettingBoolean(Activity activity, String name, boolean defaultValue){
SharedPreferences settings = activity.getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE);
return settings.getBoolean(name, defaultValue);
}
NFCLaunchActivity.java
:
import static com.mypackage.MainActivity.getSettingBoolean;
import static com.mypackage.MainActivity.shouldLaunchByNFC;
public class NFCLaunchActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView explicitly omitted
boolean launchWithNfc = getSettingBoolean(this, shouldLaunchByNFC, true);
if(launchWithNfc){
Context context = this.getApplicationContext();
Intent intent = new Intent();
intent.setClassName(context, context.getPackageName() + ".MainActivity");
context.startActivity(intent);
}
finish();
}
}
是您的要求,發動對檢測任何非NDEF標籤?或者是一種特殊的技術類型的標籤? – jgriffin
這是一個特定的代碼類型(無法精確由於NDA指定),其是NFCA(14443-3/4 A型)。但是,我需要能夠選擇停止啓動應用程序,檢測目標標記類型以及非目標標記。 – DaveAlden