Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9173783
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T16:38:40+00:00 2026-06-17T16:38:40+00:00

ive got a new problem,so is like this, i ve read the tag and

  • 0

ive got a new problem,so is like this, i ve read the tag and everything works fine,after that i put the phone on sleep/blocked.

Then i press a button to ‘wake up’ the phone, and then unblock the phone, and the activity appears, the problem is that it fires the reading again, but this time i didnt aproach a tag, its preserving the last intent.
How can this be possible? how can i delete the intent.

here is the code for the activity:

public class LerTags extends Activity {
private NfcAdapter mNfcAdapter;
private ImageView mScanner;
private Animation mAnimation;
SharedPreferences gameSettings;
String user="";
String posto="";

String content="";
String tagsvisitadassemnet="";


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);
    user=gameSettings.getString("User", "");
    posto=gameSettings.getString("Posto", "");

    //verificar que tipo de utilizador é..
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    if(posto.equals("1")==true)
        setContentView(R.layout.activity_lertags);
        else
            setContentView(R.layout.activity_lertags_noadmin);  
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);

        ((TextView)findViewById(R.id.titlebarTitleTxt)).setText(user);

        //verificar o status da conecao e por imagem correspondente
        if(isNetworkAvailable(LerTags.this)==true)
        {
              ImageView statusrede = (ImageView) findViewById(R.id.statusrede);
              statusrede.setImageResource(R.drawable.rede);
        }
        else
        {
              ImageView statusrede = (ImageView) findViewById(R.id.statusrede);
              statusrede.setImageResource(R.drawable.redeoff);

        }

        //animaçao
        mScanner = (ImageView)findViewById(R.id.img);

        mScanner.setVisibility(View.VISIBLE);
        TranslateAnimation mAnimation = new TranslateAnimation(
                 TranslateAnimation.RELATIVE_TO_SELF, -1.0f,
                 TranslateAnimation.RELATIVE_TO_SELF, 0.2f,
                 TranslateAnimation.ABSOLUTE, 0f,
                 TranslateAnimation.ABSOLUTE, 0f);
        mAnimation.setDuration(3000);
        mAnimation.setRepeatCount(-1);
        mAnimation.setRepeatMode(Animation.REVERSE);
        mAnimation.setInterpolator(new LinearInterpolator());
        mScanner.setAnimation(mAnimation);



        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(this, "Sorry, NFC is not available on this device", Toast.LENGTH_SHORT).show();
            //finish();
        }
        else
        {
        if(mNfcAdapter.isEnabled()==false)
        {
            //Toast.makeText(getApplicationContext(), "Please activate NFC and press Back to return to the application!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
            setResult(2);
            finish();

        }
        }



        Button btsair= (Button) findViewById(R.id.exit);

           btsair.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    exit();
                }
            });



}
private boolean isWriteReady = false;

  //funçao para eliminar todas as actividades
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode==2){
        setResult(2);
        finish();
    }
}

//funcao usada para sair...
 public void exit()
    {
        SharedPreferences.Editor prefEditor = gameSettings.edit(); 
        prefEditor.putString("UserName",""); 
        prefEditor.putString("Password","");  
        prefEditor.commit();
        setResult(2);
        finish();

    }

   //verificar se tem ou nao internet
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
       NetworkInfo[] info = connectivity.getAllNetworkInfo();
       if (info != null) {
          for (int i = 0; i < info.length; i++) {
             if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                return true;
             }
          }
       }
    }
    return false;
 }

@Override
public void onNewIntent(Intent intent) {
    // onResume gets called after this to handle the intent
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    setIntent(intent);


}

@Override
public void onResume() {
    super.onResume();
     //verificar o status da conecao e por imagem correspondente
    if(isNetworkAvailable(LerTags.this)==true)
    {
          ImageView statusrede = (ImageView) findViewById(R.id.statusrede);
          statusrede.setImageResource(R.drawable.rede);
    }
    else
    {
          ImageView statusrede = (ImageView) findViewById(R.id.statusrede);
          statusrede.setImageResource(R.drawable.redeoff);

    }
    tagsvisitadassemnet=gameSettings.getString("tagsvisitadas", "");
    Toast.makeText( LerTags.this, "Dados em memoria em RESUME 2:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();


        //Toast.makeText( TagsActivity2.this, "vai continuar... login:"+user, Toast.LENGTH_LONG).show();
     //Toast.makeText( LerTags.this, "REsume--tags em memoria:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
    Toast.makeText( LerTags.this, "REsume--valor do iswriteready:"+isWriteReady, Toast.LENGTH_LONG).show();
    if (isWriteReady && NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {

    } else if (!isWriteReady
            && (NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED
                    .equals(getIntent().getAction()))) {
        processReadIntent(getIntent());
    }
}

public void processReadIntent(Intent intent) {
     //Toast.makeText( LerTags.this, "process read intent"+isWriteReady, Toast.LENGTH_LONG).show();
    List<NdefMessage> intentMessages = NfcUtils.getMessagesFromIntent(intent);
    List<String> payloadStrings = new ArrayList<String>(intentMessages.size());

    for (NdefMessage message : intentMessages) {
        for (NdefRecord record : message.getRecords()) {
            byte[] payload = record.getPayload();
            String payloadString = new String(payload);

            if (!TextUtils.isEmpty(payloadString))
                payloadStrings.add(payloadString);
        }
    }

    if (!payloadStrings.isEmpty()) {
         content =  TextUtils.join(",", payloadStrings);
         //verificar se leu ou nao o conteudo da tag´

         if(content.equals(""))
         {
             //erro
             LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.customtoasterro,(ViewGroup) findViewById(R.id.toast_layout_root));

                TextView text = (TextView) layout.findViewById(R.id.texttag);
                text.setText(content);

                Toast toast = new Toast(LerTags.this);
                toast.setGravity(Gravity.FILL, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();
         }
         else
         {
             LayoutInflater inflater = getLayoutInflater();
                View layout = inflater.inflate(R.layout.customtoast,(ViewGroup) findViewById(R.id.toast_layout_root));

                TextView text = (TextView) layout.findViewById(R.id.texttag);
                text.setText("Sucesso");

                Toast toast = new Toast(LerTags.this);
                toast.setGravity(Gravity.FILL, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();

         }
        //Toast.makeText(TagsActivity2.this, "Read from tag: " + content,
    //          Toast.LENGTH_LONG).show();
        Toast.makeText( LerTags.this, "a tag tem content"+content +"e vai testar interenet", Toast.LENGTH_LONG).show();
        //ver se existe con a internet

         if(isNetworkAvailable(LerTags.this)==true) {

            //if(tagsvisitadassemnet.length()>0)
            //{
                //tem tags guardadas em memoria
                Toast.makeText( LerTags.this, "existem dados por enviar:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
            new savetagdataandtagmemory().execute(new String[] { "http://www.onetag.pt/metrodoporto/teste.php" });

            //} 
            //else
            //{ //Toast.makeText( TagsActivity2.this, "tem internet vai registar ", Toast.LENGTH_LONG).show();
            //  new savetagdata().execute(new String[] { "http://www.onetag.pt/metrodoporto/teste.php" });
            //}//estava a criar este erro por causa de ter o toast dentro do doinbackground
            //Android AsyncTask [Can't create handler inside thread that has not called Looper.prepare()]
        }
        else
        {
            //Toast.makeText( TagsActivity2.this, "n tem internet vai guardar dados:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
            Calendar c = Calendar.getInstance();


            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = df.format(c.getTime());
            SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);  
            tagsvisitadassemnet=gameSettings.getString("tagsvisitadas", "");
            tagsvisitadassemnet+=content+"/"+formattedDate+"_";
            Toast.makeText( LerTags.this, "Dados em memoria:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
            SharedPreferences.Editor prefEditor = gameSettings.edit();
            prefEditor.putString("tagsvisitadas", tagsvisitadassemnet);
            prefEditor.commit();
        }

    }
}


private class savetagdataandtagmemory extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);  

        String urlpost="http://www.onetag.pt/metrodoporto_/saveBDregistos2.php";

        ArrayList<NameValuePair> parametrospost=new ArrayList<NameValuePair>();
        parametrospost.add(new BasicNameValuePair("usuario",user));
        parametrospost.add(new BasicNameValuePair("mimecode",content));
        parametrospost.add(new BasicNameValuePair("memorytags",tagsvisitadassemnet));
        Log.i("Inicio","vai entrar no try");
        String resposta = null;
        try{
            //Toast.makeText( TagsActivity2.this, "entrou no try com o server"+urlpost, Toast.LENGTH_LONG).show();
            resposta= http.executHttpPost(urlpost, parametrospost);
            String resposta2=resposta.toString();
            resposta2=resposta.replaceAll("\\a+"," ");
            Log.i("Inicio","resposta:"+resposta2 );

        }
        catch(Exception erro)
        {
            resposta="terminou";
            return resposta;
        }
        return resposta;
    }


    @Override
    protected void onPostExecute(String result) {

         //retornou erro, por exemplo tempo excedido
         if(result.equals("terminou"))
         {
            /* String erro="";
            Log.i("Inicio","Erro:"+erro );
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.customtoasterro,(ViewGroup) findViewById(R.id.toast_layout_root));

            TextView text = (TextView) layout.findViewById(R.id.texttag);
            text.setText("Erro");

            Toast toast = new Toast(LerTags.this);
            toast.setGravity(Gravity.FILL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();*/
            Calendar c = Calendar.getInstance();


             SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             String formattedDate = df.format(c.getTime());
            SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);  
            tagsvisitadassemnet=gameSettings.getString("tagsvisitadas", "");
            tagsvisitadassemnet+=content+"/"+formattedDate+"_";
            Toast.makeText( LerTags.this, "Dados em memoria:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
            SharedPreferences.Editor prefEditor = gameSettings.edit();
            prefEditor.putString("tagsvisitadas", tagsvisitadassemnet);
            prefEditor.commit();





         }
         else
         {
             String f=result.substring(0, result.length()-4);
             Toast.makeText(LerTags.this, "Registo adicionado com sucesso::::"+f, Toast.LENGTH_LONG).show();
             if(f.equals("sucesso")==true)
             {
            //Notas="";
            //Tarefas="";
            //TarefasNFeitas="";
            /*
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.customtoast,(ViewGroup) findViewById(R.id.toast_layout_root));

            TextView text = (TextView) layout.findViewById(R.id.texttag);
            text.setText("Sucesso");

            Toast toast = new Toast(LerTags.this);
            toast.setGravity(Gravity.FILL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.setView(layout);
            toast.show();*/
            //apagar as tags da memoria
            SharedPreferences.Editor prefEditor = gameSettings.edit(); 
            prefEditor.putString("tagsvisitadas",""); 
            prefEditor.commit();
            tagsvisitadassemnet=gameSettings.getString("tagsvisitadas", "");

            //Toast.makeText( LerTags.this, "Dados em depois de enviar:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();


             }
             else
             {
                 Calendar c = Calendar.getInstance();


                 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                 String formattedDate = df.format(c.getTime());
                SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);  
                tagsvisitadassemnet=gameSettings.getString("tagsvisitadas", "");
                tagsvisitadassemnet+=content+"/"+formattedDate+"_";
                Toast.makeText( LerTags.this, "Dados em memoria:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
                SharedPreferences.Editor prefEditor = gameSettings.edit();
                prefEditor.putString("tagsvisitadas", tagsvisitadassemnet);
                prefEditor.commit();

             }







         }
    }
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T16:38:41+00:00Added an answer on June 17, 2026 at 4:38 pm

    You must add a variable to notify your program that the intent has been processed. If not then you will process the intent on every onResume. You’re almost doing it right, just add (see here):

    protected boolean intentProcessed = false;
    
    @Override
        public void onNewIntent(Intent intent) {
    
            Log.d(TAG, "onNewIntent");
    
            // onResume gets called after this to handle the intent
            intentProcessed = false;
    
            setIntent(intent);
        }
    
    @Override
        protected void onResume() {
            super.onResume();
    
            // your current stuff
    
            if(!intentProcessed) {
                 intentProcessed = true;
    
                 processIntent();
            }
    
        }
    

    This way, you’ll process the initial intent, as well as all intents (scanned tags) following – but only once per intent.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've got a problem where I'm trying to read a text file like this:
I'm pretty new to java and I've got a problem that I couldn't solve
I've got a problem: I'm writing a new WebApp without a Framework. In my
I've got a weird problem and it's most obviously due to my new status
I've got a new website moved to my server. This website uses PHP and
I've got many user controls like this: PageManageCustomers.xaml.cs: public partial class PageManageCustomers : BasePage
Hey, I've got this nice little piece of code, much like all the other
I create new logins and user in my program like this(using sql stored procedures)
I've got this script, that uploads some files, connects via ssh and does some
I've got a collection of short WAV files that I would like to process

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.