如何处理NFC开/关情况?

时间:2014-11-13 20:00:03

标签: android android-intent nfc

我的应用程序依赖NFC启用某些功能。阅读了许多StackOverflow帖子和文档后,我们似乎无法以编程方式打开或关闭NFC。

因此,我们必须做类似的事情:

if (mNfcAdapter.isEnabled()) {
    //Do what you would usually plan on doing with NFC.
} else {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("NFC Disabled")
           .setMessage(getString(R.string.nfc_disabled_plea)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                        startActivity(intent);
                    }
                })
            .setNegativeButton("Later", new DialogInterface.OnClickListener() {

                 @Override    
                 public void onClick(DialogInterface dialog, int which) {
                 }
             }).create().show();
}

我是Android开发的新手并且感到困惑。目前,我的所有NFC相关代码都在我的MainActivity的onCreated方法中,该方法将在应用程序期间保持活动状态。

这样做的正确方法是将所有代码打包到函数中,然后在我的onResume()函数中调用该函数,并检查mNfcAdapter.isEnabled()是否为真?

不确定最好的方法是什么。

1 个答案:

答案 0 :(得分:0)

如果您希望在所有活动中都使用此功能,则可以创建一个扩展Activity的类,其中包含isNfcEnabled()showNfcDialog()等方法。然后,您可以使所有活动扩展到超类。

例如:

public abstract class BaseActivity extends Activity {

    public boolean isNfcEnabled() {
        // Your logic to determine if NFC is enabled
        return true;
    }

    public void showNfcDialog() {
        // Show your dialog here
    }
}

然后,为您的每项活动......

public class MainActivity extends BaseActivity {

    @Override
    protected void onResume() {
        super.onResume();

        if (isNfcEnabled()) {
            // Do something
        } else {
            showNfcDialog();
        }
    }
}