要实现Android Q中通过NFC启动的隐私更改活动,可以按照以下步骤进行:
public class NFCActivity extends AppCompatActivity {
private NfcAdapter nfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nfc);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// 设备不支持NFC
Toast.makeText(this, "设备不支持NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
if (!nfcAdapter.isEnabled()) {
// NFC未启用
Toast.makeText(this, "请启用NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
handleIntent(getIntent());
}
@Override
protected void onResume() {
super.onResume();
enableNFCForegroundDispatch();
}
@Override
protected void onPause() {
super.onPause();
disableNFCForegroundDispatch();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) ||
NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) ||
NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
// 处理NFC标签的数据
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
// 从tag中获取数据并进行处理
// ...
// 启动隐私更改活动
Intent privacyIntent = new Intent(this, PrivacyChangeActivity.class);
startActivity(privacyIntent);
finish();
}
}
private void enableNFCForegroundDispatch() {
Intent intent = new Intent(this, NFCActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{{NfcF.class.getName()}};
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
filters[0].addDataType("text/plain");
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("MalformedMimeTypeException", e);
}
filters[0].addDataScheme("http");
nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, techList);
}
private void disableNFCForegroundDispatch() {
nfcAdapter.disableForegroundDispatch(this);
}
}
public class PrivacyChangeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_privacy_change);
// 处理隐私更改逻辑
// ...
}
}
这样,当设备通过NFC读取到符合intent-filter条件的NDEF标签时,NFCActivity将启动,并处理NFC标签的数据后启动PrivacyChangeActivity进行隐私更改。