我遇到了应用程序后台堆栈的问题,我想要实现的是当按下按钮退出时,关闭所有活动,所以当我打开应用程序并检查登录后,这个活动就会启动。如果我按下退出按钮,所有活动都关闭,现在如果我读取标签,它会启动活动,创建时的 toast 被触发,resume 上的 toast 被触发,toast onread
intent 被触发,其余的一切顺利,我可以将标签数据保存到服务器中。
现在我尝试通过单击退出按钮关闭应用程序,而不是关闭所有活动,而是转到同一个活动,然后我再次按下退出按钮并关闭应用程序。
阅读标签后如何关闭所有活动。
标签Activty2.java:
public class TagsActivity2 extends Activity {
private NfcAdapter mNfcAdapter;
private ImageView mScanner;
private Animation mAnimation;
String user="",posto="",conn="",tagsvisitadassemnet="",serverselecionado="",urlpost="",content="1a";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);
user=gameSettings.getString("User", "");
posto=gameSettings.getString("Posto", "");
conn=gameSettings.getString("Conn", "");
serverselecionado= gameSettings.getString("server", "");
//Toast.makeText( TagsActivity2.this, "servidor selecionado:"+serverselecionado, Toast.LENGTH_LONG).show();
Toast.makeText( TagsActivity2.this, "on create", Toast.LENGTH_LONG).show();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
if(posto.equals("admin")==true)
setContentView(R.layout.activity_tags2);
else
setContentView(R.layout.activity_tags2_noadmin);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
//ver conecao a internet
//qual das imagens carregar, rede on ou redeoff
if(conn.equals("yes")==true)
{
// Toast.makeText( TagsActivity2.this, "tem internet para descarregar dados...", Toast.LENGTH_LONG).show();
ImageView iv = (ImageView) findViewById(R.id.titlebarconn);
iv.setImageResource(R.drawable.rede);
//verificar se existem dados gravados durante offline
tagsvisitadassemnet=gameSettings.getString("tagsvisitadas", "");
if(tagsvisitadassemnet.length()>0)
{
// Toast.makeText( TagsActivity2.this, "existem dados offline:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
//carregar os dados e apagar
SharedPreferences.Editor prefEditor = gameSettings.edit();
prefEditor.putString("tagsvisitadas", "");
prefEditor.commit();
}
}
else
{
//Toast.makeText( TagsActivity2.this, "sem internet", Toast.LENGTH_LONG).show();
ImageView iv = (ImageView) findViewById(R.id.titlebarconn);
iv.setImageResource(R.drawable.redeoff);
}
((TextView)findViewById(R.id.titlebarTitleTxt)).setText(user);
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();
}
Button bsair= (Button) findViewById(R.id.titlebarRefreshBtn);
bsair.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = gameSettings.edit();
prefEditor.putString("User", "");
prefEditor.putString("UserName", "");
prefEditor.putString("Password", "");
prefEditor.putString("Posto", "");
prefEditor.commit();
Toast.makeText( TagsActivity2.this, "sair", Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
setResult(2);
finish();
}
});
Button bultimoscheckins= (Button) findViewById(R.id.btn_tagsvisitadas);
bultimoscheckins.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(TagsActivity2.this, Lastcheckins.class);
startActivityForResult(i, 2);
}
});
Button breadtags= (Button) findViewById(R.id.btn_opcoes);
breadtags.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(TagsActivity2.this,Opcoes.class);
startActivityForResult(i, 2);
}
});
if(posto.equals("admin")==true)
{
Button bwritetags= (Button) findViewById(R.id.btn_escrevertags);
bwritetags.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(TagsActivity2.this, WriteTags.class);
startActivityForResult(i, 2);
}
});
}
}
private boolean isWriteReady = false;
/**
* Enable this activity to write to a tag
*
* @param isWriteReady
*/
public void setTagWriteReady(boolean isWriteReady) {
this.isWriteReady = isWriteReady;
if (isWriteReady) {
IntentFilter[] writeTagFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) };
mNfcAdapter.enableForegroundDispatch(TagsActivity2.this, NfcUtils.getPendingIntent(TagsActivity2.this),
writeTagFilters, null);
} else {
// Disable dispatch if not writing tags
mNfcAdapter.disableForegroundDispatch(TagsActivity2.this);
}
}
@Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
Toast.makeText( TagsActivity2.this, "on new intent", Toast.LENGTH_LONG).show();
setIntent(intent);
}
@Override
public void onResume() {
super.onResume();
Toast.makeText( TagsActivity2.this, "on resume", Toast.LENGTH_LONG).show();
if (isWriteReady && NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {
processWriteIntent(getIntent());
} else if (!isWriteReady
&& (NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED
.equals(getIntent().getAction()))) {
processReadIntent(getIntent());
}
}
private static final String MIME_TYPE = "application/com.tapped.nfc.tag";
/**
* Write to an NFC tag; reacting to an intent generated from foreground
* dispatch requesting a write
*
* @param intent
*/
public void processWriteIntent(Intent intent) {
if (isWriteReady && NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())) {
Tag detectedTag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
// String tagWriteMessage = mTextField.getText().toString();
//byte[] payload = new String(tagWriteMessage).getBytes();
//if (detectedTag != null && NfcUtils.writeTag(
// NfcUtils.createMessage(MIME_TYPE, payload), detectedTag)) {
// Toast.makeText(this, "Wrote '" + tagWriteMessage + "' to a tag!",
// Toast.LENGTH_LONG).show();
// setTagWriteReady(false);
// } else {
// Toast.makeText(this, "Write failed. Please try again.", Toast.LENGTH_LONG).show();
// }
}
}
public void processReadIntent(Intent intent) {
Toast.makeText( TagsActivity2.this, "process read intent", 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);
//Toast.makeText(TagsActivity2.this, "Read from tag: " + content,
// Toast.LENGTH_LONG).show();
//Toast.makeText( TagsActivity2.this, "a tag tem content", Toast.LENGTH_LONG).show();
//ver se existe con a internet
if(conn.equals("yes")==true)
{
//Toast.makeText( TagsActivity2.this, "tem internet vai registar httpcon...", Toast.LENGTH_LONG).show();
httpcon2 task3 = new httpcon2();
task3.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 numa string...", 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( TagsActivity2.this, "dados guardados lidos sem net:"+tagsvisitadassemnet, Toast.LENGTH_LONG).show();
SharedPreferences.Editor prefEditor = gameSettings.edit();
prefEditor.putString("tagsvisitadas", tagsvisitadassemnet);
prefEditor.commit();
}
}
}
private class httpcon2 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
SharedPreferences gameSettings = getSharedPreferences("MyGamePreferences", MODE_PRIVATE);
serverselecionado=gameSettings.getString("server", "");
//Toast.makeText( TagsActivity2.this, " httpcon2 servidor selecionado:"+serverselecionado, Toast.LENGTH_LONG).show();
if(serverselecionado.equals("metrodoporto")==true)
{
//Toast.makeText( TagsActivity2.this, "metro do porto", Toast.LENGTH_LONG).show();
urlpost="http://www.onetag.pt/metrodoporto_/saveBDregistos.php";
}
if(serverselecionado.equals("smartcom")==true)
{
//Toast.makeText( TagsActivity2.this, "smartcom", Toast.LENGTH_LONG).show();
urlpost="http://www.onetag.pt/smartcom/saveBDregistos.php";
}
//String urlget="http://www.onetag.pt/metrodoporto/teste.php?user="+txtperson.getText().toString()+"&pass="+txtpass.getText().toString();
ArrayList<NameValuePair> parametrospost=new ArrayList<NameValuePair>();
parametrospost.add(new BasicNameValuePair("usuario",user));
parametrospost.add(new BasicNameValuePair("mimecode",content));
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)
{
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("Sucesso");
Toast toast = new Toast(TagsActivity2.this);
toast.setGravity(Gravity.FILL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
return resposta;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(TagsActivity2.this, "Registo adicionado com sucesso", Toast.LENGTH_LONG).show();
//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(TagsActivity2.this);
toast.setGravity(Gravity.FILL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
//startActivityForResult(new Intent(TagsActivity2.this, TagsActivity2.class),2);*/
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText( TagsActivity2.this, "tagsactivity2 onactivity result:"+resultCode, Toast.LENGTH_LONG).show();
if(resultCode==2){
setResult(2);
finish();
}
}
}
Manisfest.xml:
这里是对应这个活动的部分。
<activity
android:name=".TagsActivity2"
android:configChanges="orientation"
android:screenOrientation="portrait"
launchMode="singleTask"
>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/com.smartcom.onetagv4.tag2" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/com.smartcom.onetagv4.tag2" />
</intent-filter>
</activity>
代码有效,我只想按下关闭按钮,然后关闭所有活动。