android 通过NFC打开应用

该文章展示了如何在Android应用中配置manifest文件以使用NFC功能,并在MainActivity中检查和使用NfcAdapter来确保NFC服务的可用性。如果设备不支持或未开启NFC,应用将提示用户。
摘要由CSDN通过智能技术生成

1、重点

2、源代码

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

<uses-feature
      android:name="android.hardware.nfc"
        android:required="true" />
   <uses-permission android:name="android.permission.NFC" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.Life_pid">
    <activity android:name=".MainActivity">
        <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.TAG_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

    </activity>

</application>
MainActivity.java

package com.kingbright.life_pid;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.Context;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {

NfcAdapter nfcAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 获取默认的NFC控制器
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (nfcAdapter == null) {
        Toast.makeText(getApplicationContext(), "设备不支持NFC!", Toast.LENGTH_LONG).show();
        System.out.println("设备不支持NFC!");
        finish();
        return;
    }
    if (!nfcAdapter.isEnabled()) {
        Toast.makeText(getApplicationContext(), "请在系统设置中先启用NFC功能!", Toast.LENGTH_LONG).show();
        System.out.println("请在系统设置中先启用NFC功能!");
        finish();
        return;
    }
    Toast.makeText(getApplicationContext(), "正常启用APP!", Toast.LENGTH_LONG).show();
    System.out.println("正常启用APP!");



}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值