亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當應用程序關閉時,Android NFC 總是調用 onCreate

當應用程序關閉時,Android NFC 總是調用 onCreate

動漫人物 2023-06-21 13:42:04
我制作了檢測 nfc 標簽的應用程序。一切正常,當我的應用程序關閉并且我用手機掃描 nfc 標簽時,它向我顯示一個具有 onCreate() 方法的活動,當我再次掃描它的第二次工作時,我不知道我的生命周期是否錯誤應用程序或者我在代碼中遺漏了什么?當我打開應用程序時,掃描正在工作:應用程序關閉時的第一張照片第二張照片:來自第二張照片,但在第二次掃描中它有效這是我的代碼public class NfcActivity extends AppCompatActivity {    private static final String TAG = "NfcActivity";    private NfcAdapter mNfcAdapter;    private TextView mTextView;    PendingIntent pendingIntent;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_nfc);        mTextView = findViewById(R.id.tv_nfc_detail);        mNfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());        if (mNfcAdapter == null) {            Toast.makeText(this, "Cet appareil ne supporte pas nfc", Toast.LENGTH_SHORT).show();            finish();            return;        }        if (!mNfcAdapter.isEnabled()) {            startActivity(new Intent("android.settings.NFC_SETTINGS"));            Toast.makeText(this, "Activer nfc", Toast.LENGTH_SHORT).show();        }        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,            getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);    }    @Override    protected void onPause() {        super.onPause();        mNfcAdapter.disableForegroundDispatch(this);    }    @Override    protected void onResume() {        super.onResume();        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,            getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);        IntentFilter[] intentFilters = new IntentFilter[]{};        mNfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, null);    }
查看完整描述

1 回答

?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

您只是在第二次處理意圖。

添加一個基于您當前onNewIntent()方法的新方法,如下所示:

private void onNewNfcTag(Intent intent) {

? ? if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())

? ? ? ? ? ? || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())?

? ? ? ? ? ? || NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {

? ? ? ? Tag iTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

? ? ? ? mTextView.setText(TagReader.readTag(iTag, intent));

? ? }

}

更改您的onNewIntent()名稱以調用此新方法:


@Override

protected void onNewIntent(Intent intent) {

? ? super.onNewIntent(intent);

? ? onNewNfcTag(intent);

}

onCreate()從intent from調用這個相同的方法getIntent():


@Override

protected void onCreate(Bundle savedInstanceState) {

? ? // .... your code already here

? ? onNewNfcTag(getIntent());

}


查看完整回答
反對 回復 2023-06-21
  • 1 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號