앱 백스탭에 문제가 있습니다. 버튼을 누르면 모든 액티비티가 닫히므로 앱을 열고 로그인을 선택하면이 액티비티가 종료됩니다. 시작되었습니다. 나가 출구 단추를 누르면, 모든 활동은 닫힌다, 나가 지금 꼬리표를 읽는 경우에, 활동에 착수한다, 창조에 축배는 불이고, 이력서에 축배는 발사되고, 축배는 onread
의도는 발사하고, 나머지는 잘 어울린다 , 그리고 태그 데이터를 서버에 저장할 수 있습니다.
이제 종료 버튼을 클릭하여 앱을 닫고 모든 활동을 닫는 대신 동일한 활동으로 이동 한 다음 다시 exit 버튼을 누르면 앱이 닫힙니다.
어떻게 태그를 읽은 후 모든 활동을 닫을 수 있습니까?
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>
코드가 작동하며, 닫기 버튼을 누르고 모든 활동을 닫으려고합니다.
질문을 다시합니다 ... –