2013-01-21 87 views
0

我得到了一個新問題,所以是這樣的,我讀了標籤,一切正常,之後,我把手機睡覺/封鎖。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(); 

      } 







     } 
    } 
} 
} 
+0

你是什麼意思_I沒有接近tag_? –

+0

就像我說過的,如果我將手機標記爲標籤,一切正常,然後我將手機置於睡眠/待機狀態...然後離開,如果我解鎖手機,它的功能與我閱讀標籤時一樣,但是這一次,手機和標籤之間沒有任何聯繫。 –

回答

0

您必須添加一個變量來通知的意圖已經被處理程序。如果沒有,那麼你會在每個onResume上處理這個意圖。你幾乎做是正確的,只是增加(見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(); 
     } 

    } 

這樣一來,你會處理初步意向,以及以下所有的意圖(掃描標籤) - 但每個意圖只有一次。

+0

好吧,謝謝托馬斯,我會嘗試... –

+0

托馬斯,它的作品完美,至少在試驗中我一直在做,明天我會嘗試在現場... –

相關問題