launch activity twice even with launchMode="singleTask" - java

I have an activity for showing tour details with two inconsistent goals
First
that activity has a booking button which redirects to bank pay and get back to activity after successful or unsuccessful pay.that is why i set Launch Mode in manifest to stop activity from re creating.
android:launchMode="singleTask"
Second
that activity has a button which redirect to similar tour,then i have to call finish(); before startActivity() to make intent work!
onNewIntent() inside activity to get data of first part
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.getData() != null) {
Helper.logDebug("fsfsfsgsgsgs", "inside get data not null");
String query = intent.getData().getQuery();
Helper.logDebug("fsfsfsgsgsgs","query is "+ query);
if (query!=null && query.contains("Status=OK")) {
if (frgBtmReserve!=null){
frgBtmReserve.dismiss();
}
String count=query.substring(16);
Helper.logDebug("fsfsfsgsgsgs","count is "+ count);
frgObjectInfo.updateReserveCount(count);
Helper.logDebug("fsfsfsgsgsgs", "inside status ok");
Helper.notifyUserDone(getResources().getString(R.string.success_tour_reserve), this,R.drawable.ic_tick);
} else {
frgBtmReserve.dismiss();
Helper.logDebug("fsfsfsgsgsgs", "inside status nok");
Helper.notifyUserWarning(getResources().getString(R.string.error_tour_reserve), this);
}
}
}
on click of second part which should create new instance of current activity but it doesnt because of launch mode of activity which is singleTask.intent doesnt work until i finish() before startActivity()
Intent intent = new Intent(context, ActivityShowObject.class);
intent.putExtra(ActivityShowObject.INTENT_KEY_TYPE, Obj.TYPE_TRAVEL);
intent.putExtra(ActivityShowObject.INTENT_KEY_COLOR, color);
intent.putExtra(ActivityShowObject.INTENT_KEY_OBJ_ID, obj.getAgencyId());
((AppCompatActivity)context).finish();
startActivity(intent);
Animatoo.animateShrink(context);
that is my problem
think of a user which is looking into some similar tours then press back and app goes back to the very first step! do you guys have a suggestion for me?

Get rid of
android:launchMode="singleTask"
for a start. I think its the wrong usecase, making it harder for you.
You have two scenarios:
1) New activity pay for this tour
2) New activity Browse another tour
for #2 use the normal startActivity route, this will allow normal back navigation
for #1 you could also use normal startActivity but I have a feeling that when they pay successfully you do not want them to press back to go back to the tour, but if they are unsuccessful at paying you do want to allow them to go back?
If that is the case, you can use startActivityForResult when navigating to your #1 pay scenario.
When they complete payment successfully call
setResult(RESULT_OK)
if they are unsuccessful
setResult(RESULT_CANCELLED)
Then when they hit back, the result is propogated to the first activity, and you an use this to either call finish() or not.

Related

How to ensure a function does the entire check of a function?

private void startUpTasks() {
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);
// If the activity has never started before...
if (isFirstRun) {
// Launch app intro
Intent i = new Intent(LoginActivity.this, EnterInfoActivity.class);
startActivity(i);
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).apply();
initializeUserInfo();
} else {
getUserInfo();
Intent myIntent = new Intent(LoginActivity.this, SplashScreen.class);
LoginActivity.this.startActivity(myIntent);
}
}
Basically I have it narrowed down that the check goes straight to the else statement which doesn't allow a user to register for the first time. I'm using Firebase Auth to register a new user and store them in Firebase's Database.
Any ideas on how to fix this?
Okay look I will try to help you understand what you should do:
I assume that you want the user to go to EnterInfoActivity only if they didn't register before, and you are using sharedPreferences to do so. If that is the case:
This code:
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).apply();
Must be added after the user registered the details in the EnterInfoActivity
Other than that
If you want to test the functionality again, you must uninstall the app to clear shared preferences data and run the app again to test again as if you are a new user that installed the app, this way if-statement must run instead of else.

How to close current and previous one activity when user logout from app in android?

I want to close both current and previous(parent)activity when user logout from app,
But Here the problem is that when user logout from app then it redirect to login activity to ask user for login, and if user press back button then it redirect to welcome page, how to close current and previous (welcome) page at once when user get logout .
here is my logout code in menu.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Logout_secondActivity) {
session.logoutUser();
finish();
//Welcome.this.finish();
Toast.makeText(Second_activity.this, "Logout...", Toast.LENGTH_LONG)
.show();
}
}
Here is session manager for Logout user!,
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
// if user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
Here i am already use flags
You can put shared preferences boolean value from current activity and then always check if a key exist in the parent activity (check it in onPostResume method). If the key exists finish this activity and if not, just remove the key. There might be simpler and more elegant solution but this one will work for sure.
You should start the required activity with startActivity after adding these flags. These will clear the activity stack and start the new Activity as fresh one. Use your required Class name in place of Splash.class and place this code after you logout your user.
Intent i = new Intent(this, Splash.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
EDIT:
What i understood from your problem is that you want to go to HomeActivity from LoginActivity either if it is in activity stack or not. one way you can do this is to override onBackPressed in LoginAcitivty . i.e when back is pressed in LoginActivity it starts the HomeActivity. You can do it like:
#Override
public void onBackPressed() {
Intent i = new Intent(this, HomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish(); // it is optional if you want to keep the login activity in stack you should remove this line
}
call finishAffinity(); after _context.startActivity(i);
for further reference you may follow this
https://developer.android.com/reference/android/app/Activity.html
UPDATE:
if you are calling this function from non Activity class then you must pass the Activity's Context when you call it, like this _context.finishAffinity()

Notifications not show up

I am working on a messaging app, it sends user notification when he is on a different activtyon my app or is on another app but if the user is on MessagingActivity.java it just updates the chat history and does not send any notifications which is perfectly fine, but the problem arises when the user is on MessagingActivity.java meanwhile an email or something else happen user leaves the MessagingActivity.java open and checks that app if in the meantime a message comes user does not receive any notifications
public void parseRequest(Bundle extras) {
if (extras.containsKey("for") && extras.containsKey("recipientID")) {
if (Integer.parseInt(extras.getString("recipientID")) == M.getID(this)) {
switch (extras.getString("for")) {
case "chat":
if (isRunning("MessagingActivity")) {
Intent intent = new Intent("update_messages_list");
intent.putExtra("data", extras);
sendBroadcast(intent);
} else {
Intent resultIntent = new Intent(this, MessagingActivity.class);
resultIntent.putExtra("conversationID", Integer.parseInt(extras.getString("conversationID")));
resultIntent.putExtra("recipientID", Integer.parseInt(extras.getString("ownerID")));
M.showNotification(getApplicationContext(), resultIntent,
extras.getString("ownerUsername"),
extras.getString("message"),
Integer.parseInt(extras.getString("conversationID")));
}
Let me know how you are checking that your MessageActivity is Running i.e. functioning of isRunning("MessagingActivity") method. If you are setting any global boolean variable for checking this and making isRunning value false in onDestroy() method of that activity then, according to life cycle of Activity it is not called until your activity is finished i.e. in your case user just switching from MessageActivity to Mail .
I am by no means an expert, but you could just set a boolean variable by overriding the Activity's onPause() and onResume() events.
Simply set msgActivityActive to true in onResume(), false in onPause(), and change your call to:
if (isRunning("MessagingActivity") && msgActivityActive)

Pass a value from a third activity to a first

so I have a doubt, I have 3 activities, in the first one I send some data to the second one, and in the second one I send some data to the third one and finish the second one, is there a way I can finish the third activity and send some data to the first activity from the third?
This is what I'm doing in the first activity.
mStartGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(), GameInProgress.class);
i.putExtra("questionObject", questions);
startActivityForResult(i,DETAIL_REQUEST);
}
});
And in the second one after i get the extra I do this to send data to the third activity:
Intent i = new Intent(view.getContext(), StatisticsActivity.class);
i.putExtra("questionObject", questionInfo);
startActivity(i);
finish();
Now in the third I get the extras and then I:
Intent returnIntent = new Intent();
isCorrect = true;
returnIntent.putExtra("questionCorrection", isCorrect);
setResult(RESULT_OK, returnIntent);
finish();
I though this would work because when I finish the third activity the onActivityResult in the first activity method is working but when I try to access the Extras I get a nullpointerexception, so I don't know, thank you.
Sorry dude but I doubt your procedure of sending data from 3rd to 1st Activity.If data is simple string or integer. You can use Shared Preference Follow link
How to use Shared preference
Edit Shared Preference
Why Don't you also finish First activity and start new Instance of same activity through intent?

How to close an activity (finish()) from service?

i make a lock screen application.. i have some service that listen to the SMS.. when the SMS receiving command andro-lock then i display a lock screen that called by service:
here'e the service's code :
if (tempMessage[0].toString().equalsIgnoreCase("andro-lock") && tempMessage[1].toString().equals(tempPassword.toString()))
{
//Toast.makeText(ListenSMSservice.this, "Menjalankan command andro-lock", Toast.LENGTH_LONG).show();
openDatabase();
updateStatusL();
Intent myIntent = new Intent(ListenSMSservice.this,LockScreenForm.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(myIntent);
}
that code has works perfecly, but i have some problem when i try to unlock my phone.. if my service receive command andro-unlock then i must close (finish) that lockscreen.java.. i was trying many code and still not works.. what must i do to close the lockscreen activity when my service receiving command andro-unlock?? please help..
else if (tempMessage[0].toString().equalsIgnoreCase("andro-unlock") && tempMessage[1].toString().equals(tempPassword.toString()))
{
//what must i do??
//any solution??
}
Thanks for your help..
A possible solution to stop the activity would be:
Intent myIntent = new Intent(ListenSMSservice.this,LockScreenForm.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle myKillerBundle = new Bundle();
myKillerBundle.putInt("kill",1);
myIntent.putExtras(myKillerBundle);
getApplication().startActivity(myIntent);
In LockScreenForm
onCreate(Bundle bundle){
if(this.getIntent().getExtras().getInt("kill")==1)
finish();
}
You could send an intent to your activity with an extra, and the activity could read this extra and, if present, finish() itself.
Regards,
Stéphane

Categories

Resources