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();
}
}
}
}
}
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):
This way, you’ll process the initial intent, as well as all intents (scanned tags) following – but only once per intent.