This looks very similar to my previous question because it's some sort of follow up. I was not very happy with the only solution given; also, the solution was for a problem slightly different from this one. So let me try to explain the problem again...
A notification is created at boot (with a BroadcastReceiver).
My app main activity is opened and the home button is pressed (the activity will be sent to the back stack).
I pull down the status bar and press on the notification previously created at boot.
That will start some activity, different from the main one.
I press the back button and the main activity is displayed.
This is not very different from my previous question... The thing is, "main activity" was just an example. I could have opened the app main activity and then opened the about activity through a menu option and pressed the home button. The back stack would now be MainActivity ยป AboutActivity. Which means that when the back button is pressed while in "some activity" (started by pressing the notification), we would be brought to the top of the back stack, that is, the about activity.
What basically want is to prevent any other activity to be opened when I press the back button while in "some activity" (again, started by pressing the notification). I want to be brought exactly where I was, that could be the desktop or some other app's activity, but not my app's MainActivity nor AboutAcitivity cause that's not where I was, those were in the back stack, "sleeping" in the background.
I have come up with a solution, but I don't think it's very elegant and I was looking for something more, well, elegant... If you have any other suggestion, please, let me know.
Anyway, this is my proposed solution:
// I use this class for public static (or public static final) members and
// methods
public final class AppHelper {
public static final String KEY_RESUME_FROM_NOTIFICATION = "resumeFromNotification";
private static boolean sResumeFromNotification = false;
public static boolean getResumeFromNotification() {
return sResumeFromNotification;
}
public static void setResumeFromNotification(boolean resumeFromNotification) {
sResumeFromNotification = resumeFromNotification;
}
}
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(...)
}
#Override
protected void onResume() {
super.onResume();
if(AppHelper.getResumeFromNotification()) {
AppHelper.setResumeFromNotification(false);
moveTaskToBack(true);
}
}
}
public class AboutActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(...)
}
#Override
protected void onResume() {
super.onResume();
if(AppHelper.getResumeFromNotification()) {
AppHelper.setResumeFromNotification(false);
moveTaskToBack(true);
}
}
}
public class SomeActivity extends Activity {
// This will be called when the notification is pressed and the activity is
// not opened yet
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(...)
extractIntentExtras(intent);
}
// This will be called if the activity is already opened and the
// notification is pressed
#Override
protected void onNewIntent(Intent intent) {
extractIntentExtras(intent);
super.onNewIntent(intent);
}
private void extractIntentExtras(Intent intent) {
Bundle bundleExtras = intent.getExtras();
if(bundleExtras != null) {
// These intent extras are set on the Intent that starts this activity
// when the notification is pressed
AppHelper.setResumeFromNotification(bundleExtras.getBoolean(
AppHelper.KEY_RESUME_FROM_NOTIFICATION));
mRowId = bundleExtras.getLong(AgendaNotesAdapter.KEY_ROW_ID);
populateNoteUpdateFields();
}
}
}
I don't know, but this solution doesn't look very elegant to me (but it works as I expect it) and I'm looking for alternatives or for strong opinions on my proposed solution as an acceptable and good solution. Thoughts?
After doing some more reading perhaps this is the combination of flags you need:
Intent intent = new Intent(mContext, SomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);
I think that should force your SomeActivity class to be launched in a completely new task.
When launching the Activity from the notification, you can control how the Activity you are about to open is put on the back stack, and what task it's associated with with Intent flags. You can try something like:
Intent intent = new Intent(mContext, SomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
If that doesn't work, try setting a few of the other flags until you get the desired behavior.
Do you ever want your MainActivity to stay in history? If not then my simple, crude solution is to finish the MainActivity when it is paused.
(Call this in your MainActivity)
#Override
public void onPause() {
finish();
}
This will ensure that your MainActivity is removed from history when you navigate away from it, and will never appear when the back button is pressed.
This could be used for AboutActivity as well.
Related
I want to clear the HistoryStack once I have started my MainAcitivty that is inside its oncreate() method of Main.
Due to some issues I cant use android:noHistory="true" because it creates problem for my gPlus signing in, also cant use finish() FLAG_ACTIVITY_NO_HISTORY for similar reasons.
I only want it to be removes in particular case that is when inside Main, otherwise it should be there on History stack.
Once in Main all history stack should be clear and over pressing back the app should exit. Is it possible, if yes how, please explain.
For no recents activities use android:excludeFromRecents="true" in desire activity.
You could add a BroadcastReceiver in all activities you want to finish.
public class MyActivity extends Activity {
private FinishReceiver finishReceiver;
private static final String ACTION_FINISH =
"com.mypackage.MyActivity.ACTION_FINISH";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finishReceiver = new FinishReceiver();
registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH));
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(finishReceiver);
}
private final class FinishReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_FINISH))
finish();
}
}
}
You can close those Activitys by calling
sendBroadcast(new Intent(ACTION_FINISH));
Check this example for details:
http://www.hrupin.com/2011/10/how-to-finish-all-activities-in-your-android-application-through-simple-call
I am writing a calculator. There are main 2 modes: polish and reverse polish system.
Anytime MainActivity is called, I like the MainActivity to direct the user to the correct page.
public class MainActivity extends BaseActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent;
String CalculatorMode = Memory.getPreference("CalculatorMode", this);
if (CalculatorMode.equals("Calc_reverse"))
intent = new Intent(this, Calc_reverse.class);
else
intent = new Intent(this, Calc_normal.class);
startActivity(intent);
}
}
After the user is directed to Calc_normal.class or Calc_reverse.class, and if he pressed the back button, he get back to the MainActivity. But nothing happen! The onCreate() is no more called. How to fix this, and is there a better way to write this? I am trying to learn, and any help is very welcome.
Instead of onCreate() you can call your methods in onStart() which will be called anytime you navigate.
onCreate() won't be called unless the activity is destroyed, you can check the activity lifecycle.
http://developer.android.com/reference/android/app/Activity.html
onStart() activity will be visible to user but won't interact.
I have two activities: MainActivity and EventActivity.
Whenever I open my app (in MainActivity by default) and it has a certain flag in SharedPreferences, it intents to EventActivity and finishes itself. Otherwise, it only intents.
In EventActivity I have a button that, when clicked, calls finish() and goes back to EventActivity.
The problem is, when I re-open my application, it will finish the MainActivity and, when I press my custom back button, it will close the app (because the intent handle has finished).
How do I check if MainActivity didn't used finish()?
If I can do that, checking if it is finished I can intent to it.
Thanks.
Override the onDestroy method of MainActivity in that set a public static Boolean field of MainActivity. In that method set that public static field as true. Check for its value in EventActivity before you finish it i.e. when you are coming back from EventActivity to MainActivity. And fire an intent to start MainActivity from EventActivity if it's value is true. And set it's value as false in onCreate of MainActivity.
As follows:
In MainActivity.java
public class MainActivity extends Activity {
public static boolean isMainActivityDestroyed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isMainActivityDestroyed = false;
.
.
.//Do something here
}
#Override
protected void onDestroy() {
super.onDestroy();
isMainActivityDestroyed = true;
.
.
.//Do something here
}
}
In EventActivity.java
public class EventActivity extends Activity {
.
.
.//Some methods
//Method which finishes EventActivity & starts MainActivity if destroyed
public void buttonOnClick()
{
if(MainActivity.isMainActivityDestroyed)
{
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
}
}
}
If isMainActivityDestroyed becomes true then it is an indication that MainActivity used finish().
You could create your own Application class extending Application and launch the needed activity from your Application's onCreate. In manifest you would then remove the default intent filter for your MainActivity.
There are some applications in which you can logout at any point within. e.g you login and then your browse around. you use the action bar or the menu button to logout. I can call finish() at that very point but then it will just pop the last activity. Even if i move the user forward to the Home Activity, still the stack remains in memory. Is there any way to destroy the remaining stack?
The easiest way to do this is to clear the stack back to your home or first activity, and pass an identifier saying to exit the app. For example:
public class ActivityOne extends Activity {
public static final String FINISH_THIS = "FINISH_THIS";
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.hasExtra(FINISH_THIS)) {
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getIntent().hasExtra(FINISH_THIS)) {
finish();
}
}
}
public class ActivityTwo extends Activity {
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.logout) {
Intent intent = new Intent(this, ActivityOne.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(ActivityOne.FINISH_THIS, true);
startActivity(intent);
}
return true;
}
}
If ActivityOne is the root of your stack and ActivityTwo is where the user selected the option to logout, starting an intent that clears back to ActivityOne will get rid of the backstack. If you want the app to exit when logging out, you can pass an extra like I did with FINISH_THIS to signal the root/home activity to finish.
Another way to do this would be to call setResult(FINISH_THIS) where FINISH_THIS is an int identifier before calling finish(). Then in all other activities in the stack, you'd override onActivityResult and check the result to see if that activity needs to be finished. If it does, you set the result again and keep passing it down the line.
Using the intent method I outlined in the beginning is the preferred method for clearing the stack as it doesn't rely on daisy chaining results together but both options work well enough.
A quick and dirty way to do it would be onResume verify you are still logged in, if not then finish it. That way if they hit back, it will close each activity as it tries to open them. This would also prevent someone from using the app manager to re-enter your activity when you expect it to be closed.
Another idea would be read Android: Clear the back stack
In my application I have an activity class A that has a listview with a cursor adapter.
From A I can go to the activity B, by pressing a button. From B I can go back to A by pressing a button (not by pressing the BACK button). This means that a new instance of the A activity is created.
From this point, if I press the BACK key, the current A activity is destroyed and B is popped. And if I press BACk again the initial A activity is popped. I hope it is clear.
My problem is that when the second A activity is destroyed, the database connection is reseted, in a static manner. So in the end, when the initial A activity is displayed, the listview will be empty.
My question is: should I try to have a single instance for the A activities, or shoud I change the database connection (to link it with the activity instance)?
Thanks a lot
Gratzi
First Of All In class A which is carrying your ListView . on clicking any Listview call the startActivity method for the Class B Activity without calling any finish().
I hope which is you are already doing.
Now in the Second Activity The button (Not the Back Button) you are using for calling Activity A . in its clickListener for calling Activity A dont call the startActivity(intentForA) instead call the finish(); for ending the Activity B. this will resume the A activity which is paused..
I hope this will help
You will need to create 3 Activities rather than 2.
Have a MAIN activity that does not really display anything.
So You have Activity A that is your main activity that can handle the connection to the DB etc.
Then Activity B and C can be the A and B that you have used.
Activity A (Main activity) can have a static instance of itself so you can refernce it's
Variables etc -OR- you can pass data from one activity to the other using Intent.put, etc.
I prefer the global static instance way as I'm a little old school on Java.
Edit:
Forgot to mention, to handle the 'closing' of the app, either Activity B or C must also close Activity.
public class ActivityA extends Activity {
ActivityA act_a_instance;
public int some_integer = 22;
#Override
public void onCreate(Bundle savedInstanceState) {
act_a_instance = this;//Now you can reference this Activity outside
//Your creation stuff etc
}
}
public class ActivityB extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
//Your creation stuff etc
//Reference stuff from ActivityA like so :
int temp_integer = ActivityA.act_a_instance.some_integer;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.options_back:
startActivity(new Intent(this, ActivityC.class));
break;
}
}
#Override
protected void onStop() {
finish();
super.onStop();
}
}
public class ActivityB extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
//Your creation stuff etc
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.options_back:
startActivity(new Intent(this, ActivityB.class));
break;
}
}
#Override
protected void onStop() {
finish();
super.onStop();
}
}
Use below code hope this will solve your problem
Intent i = new Intent(B.this, A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);