How can I use NFC to redirect to or open my Progressive Web App?

前端 未结 2 1849
死守一世寂寞
死守一世寂寞 2020-12-30 18:05

I\'ve got a progressive web app, app.example.com created using Chrome\'s \"Add to Home Screen\" button on Android.

I have an NFC tag that ordinarily op

2条回答
  •  死守一世寂寞
    2020-12-30 18:28

    Add a helper application as a work-around:

    package com.something;
    
    import android.content.Intent;
    import android.net.Uri;
    import android.nfc.NfcAdapter;
    import android.support.annotation.Nullable;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
        private void handleNfcIntent(@Nullable Intent intent) {
            if (intent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
                //clear the intent so it doesn't come back
                intent.setAction("");
                Uri uri = intent.getData();
                if (uri != null) {
                    Intent uriOnlyIntent = new Intent(Intent.ACTION_VIEW, uri);
                    //call the progressive web app registered to view the uri
                    startActivity(uriOnlyIntent);
                }
            }
        }
    
        @Override
        protected void onNewIntent(final Intent intent) {
            super.onNewIntent(intent);
            setIntent(intent);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            //https://stackoverflow.com/a/36942185 provided the insight for handling this way
            //always called after onNewIntent and onCreate allowing a tag reward for a closed app
            handleNfcIntent(getIntent());
    
        }
    }
    

    Your AndroidManifest.xml listens for your target url:

    
    
        
            
                
                    
                    
                
                
                    
                    
                    
                
            
        
    
    

    Now when you scan your tag, the NFC Intent will be handled by the installed app which forwards to the View Intent which your Progressive Web App is registered.

    For me, this only worked in Android 8, not Android 6 since apparently opening a PWA by clicking on a link in Chrome is also not supported.

    An unfortunate work-around so I'm hoping to see a better answer.

提交回复
热议问题