关闭从新意图启动的活动

时间:2012-12-25 20:59:11

标签: android nfc

我遇到app backstack的问题,我想要实现的是当按下按钮退出时,关闭所有活动,所以当我打开应用程序并在登录检查后,此活动启动。如果我按下退出按钮,所有活动都会关闭,现在如果我读取标签,它会启动活动,创建的烤面包是火,恢复烤面包,烤面包onread意图被触发,其余的一切顺利,我可以将标签数据保存到服务器中。

现在我尝试通过单击退出按钮关闭应用程序,而不是关闭所有活动,它会转到相同的活动,然后我再次按下退出按钮,应用程序关闭。

如何在阅读标签后关闭所有活动 的 TagsActivty2.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>

代码有效,我只想按关闭按钮,然后关闭所有活动。

4 个答案:

答案 0 :(得分:1)

如果是NFC意图,则会创建一个包含活动新实例的新任务堆栈。这解释了您观察到的行为:退出时,将再次显示另一个(较早的)实例。为防止这种情况发生,您可以使用android:launchmode=singleTask在清单中声明活动(请参阅http://developer.android.com/guide/topics/manifest/activity-element.html#lmode)。但是,这可能会在您的应用中产生其他副作用,因为活动只能位于活动堆栈的根目录中。

答案 1 :(得分:1)

我通过这样做来解决这个问题:

startActivityForResult(i, 2); 

启动活动时,按下退出按钮时我正在执行此操作

setResult(2);
finish();

在我所有的活动中,处理代码:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(resultCode==2){
        setResult(2);
        finish();
    }
}

答案 2 :(得分:0)

你可以试试这个:这适用于我的NFC项目!

@Override
public void onResume(){
super.onResume();
//bla bla do what you want to do, like write a tag or read it 
finish();
}
}

玩得开心!

答案 3 :(得分:-1)

如果我理解你的问题,而我不知道我这样做......我认为你所说的是背书?有一个backstack - 您可能希望将finishOnTaskLaunch或noHistory应用于该活动。我还没看完你的所有代码。

我发现很难准确理解问题所在......希望这有帮助