手机重新启动后保留 NFC 意图



>我遇到了一个新问题,所以就像这样,我已经阅读了标签,一切正常,之后我将手机置于睡眠/阻止状态。

然后

我按下一个按钮"唤醒"手机,然后取消阻止手机,活动出现,问题是它再次触发读取,但这次我没有标记,它保留了最后一个意图。这怎么可能?如何删除意向。

下面是该活动的代码:

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();
             }



         }
    }
}
}

必须添加一个变量来通知程序已处理意图。如果没有,那么您将在每次简历上处理意图。你几乎做对了,只需添加(见这里):

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();
        }
    }

这样,您将处理初始意图以及随后的所有意图(扫描的标签),但每个意图只能处理一次。