0

I have asked multiple questions on SO regarding different problems I am having with onNewIntent method in both fragments and activities. My problem now is that onNewIntent in Activity is never being called no matter what I do. The Activity that has the onNewIntent contains multiple tabs. My tabs (Fragments) contain codes for writing and reading NFC tag.

This is the code for the Activity:

    public class MyAppHome extends AppCompatActivity {

    protected DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mtoggle;
    NfcAdapter nfcAdapter;
    private Toolbar mtoolbar;
    private TextView mName;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private NavigationView mNavigationView;

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

        mtoolbar = (Toolbar) findViewById(R.id.nav_action);
        setSupportActionBar(mtoolbar);
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        mNavigationView= (NavigationView)findViewById(R.id.nav_view);
        mDrawerLayout = findViewById(R.id.drawer_layout);
        mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mDrawerLayout.addDrawerListener(mtoggle);
        mtoggle.syncState();
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition())
                {
                    case 0:
                        mViewPager.setCurrentItem(0);
                        mtoolbar.setTitle("Home");
                        break;

                    case 1:
                        mViewPager.setCurrentItem(1);
                        mtoolbar.setTitle("Writer");
                        break;

                    case 2:
                        mViewPager.setCurrentItem(2);
                        mtoolbar.setTitle("Reader");
                        break;

                    case 3:
                        mViewPager.setCurrentItem(3);
                        mtoolbar.setTitle("Others");
                        break;

                    case 4:
                        mViewPager.setCurrentItem(4);
                        mtoolbar.setTitle("Alarm");
                        break;


                    default:
                        mViewPager.setCurrentItem(tab.getPosition());
                        mtoolbar.setTitle("My APP");
                        break;
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        NavigationView navigationView = findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                // set item as selected to persist highlight
                menuItem.setChecked(true);

                switch (menuItem.getItemId()){

                    case R.id.nav_home:
                        mViewPager.setCurrentItem(0);
                        mDrawerLayout.closeDrawers();
                        mtoolbar.setTitle("Home");
                        break;

                    case R.id.nav_writer:
                        mViewPager.setCurrentItem(1);
                        mDrawerLayout.closeDrawers();
                        mtoolbar.setTitle("Writer");
                        break;

                    case R.id.nav_medication:

                        mViewPager.setCurrentItem(2);
                        mDrawerLayout.closeDrawers();
                        mtoolbar.setTitle("Reader");
                        break;

                    case R.id.nav_missedPill:
                        mViewPager.setCurrentItem(3);
                        mDrawerLayout.closeDrawers();
                        mtoolbar.setTitle("Others");
                        break;

                    case R.id.nav_alarm:
                        mViewPager.setCurrentItem(4);
                        mDrawerLayout.closeDrawers();
                        mtoolbar.setTitle("Alarm");
                        break;

                    case R.id.nav_logout:
                        FirebaseAuth.getInstance().signOut();
                        finish();
                        startActivity(new Intent(getApplicationContext(),Login.class));

                }
                // close drawer when item is tapped
                mDrawerLayout.closeDrawers();
                return true;
            }
        });

        mDrawerLayout.addDrawerListener(
                new DrawerLayout.DrawerListener() {
                    @Override
                    public void onDrawerSlide(View drawerView, float slideOffset) {
                        // Respond when the drawer's position changes
                    }

                    @Override
                    public void onDrawerOpened(View drawerView) {
                        // Respond when the drawer is opened
                    }

                    @Override
                    public void onDrawerClosed(View drawerView) {
                        // Respond when the drawer is closed
                    }

                    @Override
                    public void onDrawerStateChanged(int newState) {
                        // Respond when the drawer motion state changes
                    }
                }
        );
               initNFC(getIntent());
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_dosis_home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
           if(mtoggle.onOptionsItemSelected(item)){
                return true;
            }
            //noinspection SimplifiableIfStatement
            if (item.getItemId()== R.id.action_settings) {
                return true;
               }
            return super.onOptionsItemSelected(item);
                 }

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

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this.getApplicationContext(), this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        if(nfcAdapter !=null){
            Log.d("W", "nfcadapter is not null");
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
        }

    }

 @Override
    public void onPause() {
        super.onPause();
        if(nfcAdapter !=null){
            disableForegroundDispatchSystem();
        }

    }
public boolean write2NFC(MyNfcMessage m ) {

        NdefMessage ndefMessage = createNdefMessage(m.key1, m.key2,m.key3);
        writeNdefMessage(tag, ndefMessage);
        return true;
    }

    private void initNFC(Intent intent) {
        if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
            // if (nfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            //Toast.makeText(getActivity(), "NfcIntent!", Toast.LENGTH_SHORT).show();
            tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

  protected void onNewIntent(Intent intent) {

        System.out.print("I am here in Home");
        Log.d("my tag", "I am here now");
        initNFC(intent);
        Log.d("my tag ", "onNewIntent: something ");

}



     private void disableForegroundDispatchSystem() {
                nfcAdapter.disableForegroundDispatch(this);
            }

            private void formatTag(Tag tag, Nde

fMessage ndefMessage) {
            try {

                NdefFormatable ndefFormatable = NdefFormatable.get(tag);

                if (ndefFormatable == null) {
                    Toast.makeText(this, "Tag is not ndef formatable!", Toast.LENGTH_SHORT).show();
                }

                else{
                    ndefFormatable.connect();
                    ndefFormatable.format(ndefMessage);
                    ndefFormatable.close();
                    Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Log.e("formatTag", e.getMessage());
            }

        }

        private void writeNdefMessage(Tag tag, NdefMessage ndefMessage) {

                try {

                    if (tag == null) {
                        Toast.makeText(this, "Tag object cannot be null", Toast.LENGTH_SHORT).show();
                        return;
                }

                Ndef ndef = Ndef.get(tag);

            if (ndef == null) {
                // format tag with the ndef format and writes the message.
                formatTag(tag, ndefMessage);


        } else {
                    ndef.connect();
                    if (!ndef.isWritable()) {
                        Toast.makeText(this, "Tag is not writable!", Toast.LENGTH_SHORT).show();

                        ndef.close();
                        return;
                    }

                    ndef.writeNdefMessage(ndefMessage);
                    ndef.close();

                    Toast.makeText(this, "Tag writen!", Toast.LENGTH_SHORT).show();

                }

            } catch (Exception e) {
                Log.e("writeNdefMessage", e.getMessage());
            }

        }

        private NdefRecord createTextRecord(String content) {
                try {
                    byte[] language;
                    language = Locale.getDefault().getLanguage().getBytes("UTF-8");

                    final byte[] text = content.getBytes("UTF-8");
                    final int languageSize = la

nguage.length;
                final int textLength = text.length;
                final ByteArrayOutputStream payload = new ByteArrayOutputStream(1 + languageSize + textLength);

                payload.write((byte) (languageSize & 0x1F));
                payload.write(language, 0, languageSize);
                payload.write(text, 0, textLength);

                return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload.toByteArray());

            } catch (UnsupportedEncodingException e) {
                Log.e("createTextRecord", e.getMessage());
            }
            return null;
        }

         private NdefMessage createNdefMessage(String content, String content2, String content3) {

                NdefRecord ndefRecord = createTextRecord(content);
                NdefRecord ndefRecord2 = createTextRecord(content2);
                NdefRecord ndefRecord3 = createTextRecord(content3);

                NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{ndefRecord, ndefRecord2, ndefRecord3});

                return ndefMessage;
            }

                /**
                 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
             * one of the sections/tabs/pages.
             */
            public class SectionsPagerAdapter extends FragmentPagerAdapter {
                private List<Fragment> mFragments = new ArrayList<>();

                public SectionsPagerAdapter(FragmentManager fm) {
                    super(fm);
                    mFragments.add(new Home());
                    mFragments.add(new Writer());
                    mFragments.add(new Reader());
                    mFragments.add(new Others());
                    mFragments.add(new Alarm());
            }

            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }

            /*to set text instead of icons*/
            public CharSequence getPageTitle(int position){
                return null;
            }
        }

    }

My AndroidManifest looks something like this:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />

<uses-feature
    android:name="android.hardware.fingerprint"
    android:required="false" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:launchMode="singleTop"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".WelcomeActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".FingerPrint"
        android:screenOrientation="portrait" />
    <activity
        android:name=".MyAppHome"

        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="android.nfc.action.TAG_DISCOVERED" />
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <data android:mimeType="text/plain" />
        </intent-filter>

        <meta-data
            android:name="android.nfc.action.TECH_DISCOVERED"
            android:resource="@xml/nfc_tech_filter" />
    </activity>
    <activity
        android:name=".Login"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" />
</application>

Home Fragment (tab) is used to write information to NFC tag:

    public class Home extends Fragment {
    NfcAdapter nfcAdapter;
    Button writebtn;
    Tag tag;
    EditText txtName, txtCountry, txtID;

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view,savedInstanceState);

    }



      @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
            View v= inflater.inflate(R.layout.home, container,false);
             txtName = (EditText)view.findViewById(R.id.pName);
            txtCountry= (EditText)view.findViewById(R.id.pCountry);
            txtID= (EditText)view.findViewById(R.id.pID);
            writebtn=(Button)view.findViewById(R.id.nfcWriteBtn);

writebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyAppHome homeActivity = (MyAppHome)getActivity();

                MyNfcMessage message = new MyNfcMessage(txtName.getText().toString(), txtCountry.getText().toString(), txtID.getText().toString());
                homeActivity.write2NFC(message);

            }
        });
 return v;

        }

I don't Understand Why onNewIntent in the Activity is never being called (No Toasts are being displayed on screen). Does it have something to do with my layout?

Update: The problem was solved by creating a new project and copying all the code from the old project to the new one.

DaGuy
  • 65
  • 1
  • 6
  • Why do you think `onNewIntent()` should be called? What do you think should trigger that method being called? Please explain. – David Wasser Apr 09 '18 at 13:11
  • It should be triggered when the NFC tag is placed close to the phone – DaGuy Apr 10 '18 at 15:40
  • If your app is not running, does scanning the NFC tag start your app (ie: launch `MyAppHome` activity)? – David Wasser Apr 10 '18 at 17:00
  • Also, does `onResume()` get called if the app is already running and you scan the NFC tag? – David Wasser Apr 10 '18 at 17:01
  • Can you even launch your app from the HOME screen? Since you are missing the `ACTION_MAIN` from your ``, I don't think you can. – David Wasser Apr 10 '18 at 17:11
  • my thought for the application (project) is to launch the application from the home screen(app drawer) and then the user can write and read data to/from the NFC tag. but the problem that i am facing is that when i place the tag close to phone nothing happens (no toasts or logs are being displayed). – DaGuy Apr 10 '18 at 17:56
  • My application starts at a intro slider -> Login screen -> "MyAppHome" – DaGuy Apr 10 '18 at 18:07
  • The onResume () does not seem to be working when the application is already running. it only works when I have closed the application and then place the nfc tag close to phone (then i can write but otherwise it doesnt work) – DaGuy Apr 10 '18 at 18:11
  • I'm still confused about what you are trying to do. Please post your entire manifest – David Wasser Apr 10 '18 at 19:47
  • I have updated the code a little bit since 1 h ago (moved the nfc logic from fragment to activity). I will update the whole code. – DaGuy Apr 10 '18 at 19:49
  • Now it is updated – DaGuy Apr 10 '18 at 20:14
  • 1
    I got it to work by creating a new project and copying the entire code from one project to another – DaGuy Apr 11 '18 at 14:22
  • Well I'm glad you were able to do that, because I was pretty stumped why it wasn't working before. In any case, you should remove the `` from the `` on `MyAppHome`. This is unnecessary. – David Wasser Apr 11 '18 at 15:28
  • thnx man for your support :D – DaGuy Apr 11 '18 at 15:48
  • I am stuck now with another hiccup which is the reading NFC tag – DaGuy Apr 11 '18 at 22:31
  • Please open a new question regarding your problems with NFC. Try not to post all your code, just the relevant bits. If you post too much code, noone will read it and you will get no help. – David Wasser Apr 12 '18 at 10:12
  • Please also post an answer to this question, explaining how you solved the problem. Accept that answer. That will remove this question from the list of open questions. – David Wasser Apr 12 '18 at 10:13

1 Answers1

-1

Check this:

http://www.helloandroid.com/tutorials/communicating-between-running-activities

In manifest.xml, in an activity tag set launchmode="singleTask"

Asteroid
  • 718
  • 7
  • 21
  • It doesn't work. I have tried singleTask before and always the same results(The Toasts and logs in activity never gets displayed) – DaGuy Apr 09 '18 at 07:54
  • special launch modes (like `singleTask`) should not be used for this. There is no reason that the problem cannot be solved in another way. Special launch modes cause more problems than they solve. – David Wasser Apr 09 '18 at 13:08