I have an Android App with a number of activities. The wrong activity is being started sometimes.
Normally, an Application subclass starts, then start activity (StartAct... android:name="android.intent.action.MAIN", android:name="android.intent.category.LAUNCHER")
does some work and then launches InitializeActivity. This does some work and then fires off my main display activity (MainAct). The first two activities do some essential initialization including setting a static "isInitialized" flag just before the intent is launched for the MainAct.
Activities are launched with startActivity() using a specific intent (...activity.class specified), and call finish() after startActivity().
However, here is what sometimes happen, and I don't know why...
In short, the app is killed and when the icon is pressed to start it, it jumps straight to the third (MainAct) activity. This causes the app to detect an error (isInitialized flag is false) and stop:
Launch the app normally with the Icon:
...Application subclass starts, also fires up some worker threads
...StartActivity runs, then fires InitializeActivity and finishes
...InitializeActivity runs, then sets isInitialized and starts MainAct and finishes
...MainAct starts, runs okay
...Home button is hit and Angry Birds is run
...MainAct logs onPause, then onStop.
...Worker threads owned by Application subclass continue to periodically do stuff and log.
After 25 minutes, the entire application is suddenly killed. This observation is based on thhe end of logging activity,
Time goes by
Home button hit
Launcher ICON is pressed for the app
Application subclass onCreate is called and returns
*MainAct.onCreate is called! (no StartAct, no InitializeActivity)*
What am I missing?
Note: the initialize flag was added because of this issue. It is set in the only place in the code that starts the main activity, and checked only in onCreate in the main activity.
[per request]
Manifest file (slightly redacted). Note that the service in here is not currently used.
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="xxx.yyy.zzz"
android:versionCode="1" android:versionName="1.0.1">
<application
android:icon="#drawable/icon_nondistr"
android:label="#string/app_name"
android:name=".app.MainApp"
android:debuggable="true">
<activity
android:label="#string/app_name"
android:name=".app.StartAct" android:theme="#android:style/Theme.NoTitleBar">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="Html"
android:name=".app.HtmlDisplayAct"/>
<activity
android:label="Init"
android:configChanges="orientation"
android:name=".app.InitializeActivity" android:theme="#android:style/Theme.NoTitleBar"/>
<activity
android:label="MyPrefs"
android:name=".app.PrefsAct" />
<activity
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar"
android:name=".app.MainAct">
</activity>
<service
android:name=".app.svcs.DataGetterService" />
</application>
<uses-sdk android:minSdkVersion="4"/>
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="com.android.vending.CHECK_LICENSE" />
<uses-feature
android:name="android.hardware.location.network"
android:required="false" />
</manifest>
The fact that the application is killed because of low memory should be transparent to the users. This is why when the application is killed, Android remembers what was the last activity running in this application, and creates directly this activity when the user returns to the application.
Perhaps you could do something in the onCreate() method of your Application (or of your MainAct) to ensure that everything is properly initialized.
By the way, unless you really need to, you shouldn’t have worker threads doing some work when the user is not using your application. Depending on what you do this could drain the battery quickly, or make the user think that it could drain the battery quickly (which is worse, because the user will uninstall your app!)
You could also make the application finish every activity when the user is quitting the application,
This is really a case of "adding insult to injury" - first Android kills my awesome app, and then when the user restarts my app Android tries to be "helpful" by launching the wrong activity, causing my app to crash. Sigh.
Here is my very kludgy workaround to counteract Android's helpfulness. My app requires that StartActivity must be the first activity, so for all other activities I add one line to the onCreate() method. For example:
public class HelpActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (StaticMethods.switchToStartActivityIfNecessary(this)) return; // <- this is the magic line
...
}
...
}
To make this work I've added a switch variable to my Application class:
public class OutBackClientApplication extends Application {
...
// Switch to indicate if StartActivity has been started.
// Values: -1 = StartActity has never been started or this is first invocation.
// 0 = normal situation, StartActivity has been run at least once.
private int _startActivityStatus = -1;
public int getStartActivityStatus() { return _startActivityStatus; }
public void setStartActivityStatus(int startActivityStatus) {
_startActivityStatus = startActivityStatus;
}
...
}
And I have a class called StaticMethods, which includes the following method:
public class StaticMethods {
/**
* Method to test for the problematic situation where Android has previously killed this app, and
* then when the user restarts the app Android tries to be helpful by restarting the activity
* that was in the foreground when it killed the app, instead of starting the activity specified
* in the manifest as the launch activity. See here:
* http://stackoverflow.com/questions/6673271/android-wrong-activity-sometimes-starts
*
* The following line should be added to the onCreate() method of every Activity, except for
* StartActivity, of course:
*
* if (StaticMethods.switchToStartActivityIfNecessary(this)) return;
*/
public static boolean switchToStartActivityIfNecessary(Activity currentActivity) {
OutBackClientApplication outBackClientApplication =
(OutBackClientApplication) currentActivity.getApplication();
if (outBackClientApplication.getStartActivityStatus() == -1) {
currentActivity.startActivity(new Intent(currentActivity, StartActivity.class));
currentActivity.finish();
return true;
}
return false;
}
}
Finally, when StartActivity starts it needs to reset the switch:
public class StartActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((OutBackClientApplication) getApplication()).setStartActivityStatus(0);
...
}
...
}
All that, just to counteract Android's "helpfulness" ...
Related
I have an application that starts with an Activity to load stuff before the main Activity is shown. Starting the application normally does MyApplication --> MyLoadingActivity --> MyMainActivity. In MyMainActivity there is a ViewPager with RecyclerViews and other stuff. The state in MyMainActivity is properly saved and restored when navigation to and from other Activities in the application, but when starting MyMainActivity from a Notification all the state is cleared since Android restarts that Activity.
The Notifications are created from a Service checking for updates from a remote server. Once updates are found, the new data are stored in the SQLite database and a Notification about this is created. When I click this Notification, MyMainActicity is started, but the state is lost.
Following the official guide, here is how I create the Notification inside the Service:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.foo)
.setAutoCancel(true)
.setContentTitle("title")
.setContentText("text")
.setStyle(new NotificationCompat.BigTextStyle().bigText("A long text will go here if we are on Lollipop or above."));
Intent notifyIntent = new Intent(context, MyMainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifyPendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(notifyPendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(666, builder.build());
I have tried combining the Intent.FLAG_*** in various ways, but I have not been able to make it work properly. I cannot figure this out, hence this question.
What I want to achieve when opening the Notification is:
If the application is not running, start the application normally and go to MyMainActivity.
If the application is running and MyMainActivity is active, just bring that to the front with the existing state and run a few lines of code.
If the application is running and another Activity is running, go back to MyMainActivity, preferably using the existing stack. Most other activities are children of MyMainActivity.
What happens using the current code:
Using Intent.FLAG_ACTIVITY_NEW_TASK creates a new instance of MyMainActivity which has empty state, even though its description states
When using this flag, if a task is already running for the activity
you are now starting, then a new activity will not be started;
instead, the current task will simply be brought to the front of the
screen with the state it was last in.
Also using Intent.FLAG_ACTIVITY_CLEAR_TASK calls onDestroy() on the existing MyMainActivity after the new MyMainActivity is created. That does not help much.
What other things I have tried:
A. Setting the Intent to start as the Application normally does, as described here, does not work.
B. Various combinations of flags has not been able to give the desired behavior.
C. Various other answers here on Stackoverflow.
For reference, here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/my_app_name"
android:theme="#style/MyTheme"
android:name=".MyApplication" >
<activity
android:name=".activities.MyLoadingActivity"
android:icon="#drawable/ic_launcher"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.MyMainActivity"
android:icon="#drawable/ic_launcher"
android:label="#string/my_app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name=".activities.AnotherActivity"
android:label="#string/aa_title"
android:icon="#drawable/ic_launcher"
android:parentActivityName=".activities.MyMainActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.MyMainActivity" >
</meta-data>
</activity>
<!-- More children activities of MyMainActivity here -->
<receiver android:name=".services.ScheduleUpdateReciever">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="com.my.app.action.ScheduleUpdateReceiver"/>
</intent-filter>
</receiver>
<receiver android:name=".services.StartUpdateReceiver" />
<service android:enabled="true" android:name=".services.UpdateService" />
</application>
</manifest>
Update: saving/restoring
Here is how MyMainActivity is saved and restored. I realize that this might need some cleaning. Maybe it is related to the problems. Other parts of the class is omitted for brevity. As noted above, all of the saving and restoring works fine when navigating around inside the app.
private ShoppingList mShoppingList;
private FilteredRecipes mFilteredRecipes;
private MainFragment mMainFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
// Start the Broadcast receiver that creates notifications if new data is found.
startService(new Intent(this, ScheduleUpdateReciever.class));
sendBroadcast(new Intent(SCHEDULE_UPDATE_RECEIVER_BROADCAST));
// Setup Toolbar, NavigationView, DrawerLayout etc. here. No state restored for these widgets.
if (mShoppingList == null)
{
mShoppingList = new ShoppingList(this);
}
if (mFilteredRecipes == null)
{
mFilteredRecipes = new FilteredRecipes(this);
}
if (savedInstanceState == null)
{
mMainFragment = new MainFragment();
}
else
{
restoreState(savedInstanceState);
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mMainFragment, FragmentConstants.MAIN_FRAGMENT_TAG)
.commit();
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
// These calls adds stuff directly to the Bundle instance, be it basic variables, lists or Parcelable classes.
mShoppingList.onSaveInstanceState(outState);
mFilteredRecipes.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, SAVE_RESTORE_MAIN_FRAGMENT, mMainFragment);
}
private void restoreState(Bundle savedInstanceState)
{
// These calls restores stuff directly from the Bundle instance, be it basic variables, lists or Parcelable classes.
mShoppingList.onRestoreInstanceState(savedInstanceState);
mFilteredRecipes.onRestoreInstanceState(savedInstanceState);
mMainFragment = (MainFragment) getSupportFragmentManager().getFragment(savedInstanceState, SAVE_RESTORE_MAIN_FRAGMENT);
}
From the android documentation: http://developer.android.com/reference/android/content/Intent.html
About FLAG_ACTIVITY_CLEAR_TOP:
If set, and the activity being launched is already running in the
current task, then instead of launching a new instance of that
activity, all of the other activities on top of it will be closed and
this Intent will be delivered to the (now on top) old activity as a
new Intent.
About FLAG_ACTIVITY_SINGLE_TOP:
If set, the activity will not be launched if it is already running at
the top of the history stack.
It sound pretty much of what you are attempting to achieve. Try this:
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
EDIT:
You are using savedInstanceState to save the data from your activity, I don't recommend to use this approach because it isn't reliable, from the documentation (http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState%28android.os.Bundle%29) you can infer that onSaveInstanceState() could not be called at all:
Do not confuse this method with activity lifecycle callbacks such as
onPause(), which is always called when an activity is being placed in
the background or on its way to destruction, or onStop() which is
called before destruction. One example of when onPause() and onStop()
is called and not this method is when a user navigates back from
activity B to activity A: there is no need to call
onSaveInstanceState(Bundle) on B because that particular instance will
never be restored, so the system avoids calling it. An example when
onPause() is called and not onSaveInstanceState(Bundle) is when
activity B is launched in front of activity A: the system may avoid
calling onSaveInstanceState(Bundle) on activity A if it isn't killed
during the lifetime of B since the state of the user interface of A
will stay intact.
You should use a more persistent way to store your key/value information, such as sharedPreferences or a database and retrieve those values in your onCreate method. There is more information about it here: http://developer.android.com/training/basics/data-storage/index.html
You can also check my answer here: https://stackoverflow.com/a/35023304/5837758 for an easy way to use sharedPreferences.
I would like to launch my application and check the connectivity state in application's onCreate method then decide which activity to start! I know that I could finish() a default MAIN/LAUNCHER activity before to setLayout while starting another if it's relevant but that seems messy to me!
So, I would like to know if it is possible to start an application whose doesn't manifest an activity with action.MAIN / category.LAUNCHER? I tried this way but it doesn't work! I mean the application seems to start but no activity is shown!
(This is not a sample from my real code, I'm not at home right now! Some arguments and stuff may be missing but I think you get the point!)
public class MyApp extends Application {
onCreate() {
Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.NEW_TASK);
this.startActivity(intent);
}
}
Also, the first activity of my application may be an AlertDialog and I'm wondering if I can start one while no activity is started or if I'm forced to set an activity's theme with #android:style/Theme.Dialog?
I tried the same as for the above example but same result : logcat saying application alive while no printing at all...
Tell me if I'm not clear enough and in which way! I'm not an english speaker and I'm not used to ask in forums!
You will have to go this way:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.some_empty_or_loading_view); //optional probably, not sure
//TODO: check whatever you want
if(condition) {
startActivity(this, SomeActivity.class);
} else {
startActivity(this, AnotherActivity.class);
}
finish();
}
}
Specify Your App's Launcher Activity
When the user selects your app icon from the Home screen, the system calls the onCreate() method for the Activity in your app that you've declared to be the "launcher" (or "main") activity. This is the activity that serves as the main entry point to your app's user interface.
You can define which activity to use as the main activity in the Android manifest file, AndroidManifest.xml, which is at the root of your project directory.
The main activity for your app must be declared in the manifest with an that includes the MAIN action and LAUNCHER category. For example:
<activity android:name=".MainActivity" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Note: When you create a new Android project with the Android SDK tools, the default project files include an Activity class that's declared in the manifest with this filter.
If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of app
I am developing simple application with only two activities.
Activity C configures application
Activity A for interaction with user when some event occur
It is not possible for user to navigate from the one to the other - this is why I call them independent activities. Further more activity A is being invoked only form event, there is no way for user to do it manually.
Problem. Let's assume that application is properly configured. Some event occurs in the system, so application A is being shown to the user. The user interact with it and activity goes to background. Then the user decides to launch configuration activity C. Activity C is shown to the user. The user uses back button to "close" activity, but instead of android launcher or desktop the user is being shown activity A (taken from history).
Similar scenario might happen the other way. C is being used by user, then taken to background. Some event shows activity A and user using back button goes to C instead of closing activity A.
I have solved the problem, but the solution is pretty dirty. Is there any clean or standard way of solving such problem?
Part of my solution includes what was suggested in one answer:
snippet from AndroidManifest.xml:
<activity
android:name=".C"
android:clearTaskOnLaunch="true"
android:excludeFromRecents="false"
android:launchMode="singleTask"
...
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:exported="false"
android:name=".A"
android:excludeFromRecents="true"
android:noHistory="true"
android:launchMode="singleInstance"
android:clearTaskOnLaunch="true"
....
>
</activity>
snippet from activity A:
public boolean onKeyUp(final int p_keyCode, final KeyEvent p_event) {
switch(p_keyCode) {
case KeyEvent.KEYCODE_ENDCALL:
case KeyEvent.KEYCODE_HOME:
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_MUTE:
case KeyEvent.KEYCODE_POWER:
this.finish();
break;
....
}
return super.onKeyUp(p_keyCode, p_event);
}
snipped from event handler:
public class H extends BroadcastReceiver {
...
Intent intent = new Intent(p_context, A.class);
intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
p_context.startActivity(intent);
...
}
It works for my application. However I want application (activity C) to appear in Recent application. But once activity A is invoked application is removed from Recent.
I don't know if this is the cleanest way to do this, but you can override the void onBackPressed() activity method. This way you can mannually move your activity to the background, like this, and prevent the previous activity from popping in:
public void onBackPressed () {
moveTaskToBack (true);
}
Edit: Turns out there's a better way to do this:
Open your AndroidManifest.xml, and inside each declaration put the following: `android:noHistory="true"``. Doing so will tell Android that your activity does not leave a history, and therefore, when the user hits back Android will quit the application, since there's no other activity for it to return to.
I am having a strange problem in an Android application that I am building, the application is basically a Homescreen replacement app which will be put as a default homescreen in a device. To do some initialization work I have extended Android Application class and in the onCreate() method I am basically registering some observer and starting a service, here's the code:
public class MyApplication extends Application implements ExternalStorageListener {
private ExternalStorageObserver externalStorageObserver;
public void onCreate() {
Log.i("MyApplication", "Starting application");
super.onCreate();
externalStorageObserver = new ExternalStorageObserver(this);
if(externalStorageObserver.isExternalStorageAvailable()) {
// this builds a list of files present in the SD card
// which is being used through the application to do
// some work
buildData();
File externalFileDir = getApplicationContext().getExternalFilesDir(null);
if(externalFileDir != null && externalFileDir.isDirectory()) {
// do something...
}
}
//Register listener to observe external storage state
registerExternalStorageObserver();
Log.i("SyncService", "Starting sync service...");
ComponentName cmp = startService(new Intent(getApplicationContext(), SyncService.class));
Log.i("SyncService", cmp.toString());
}
private void registerExternalStorageObserver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
registerReceiver(externalStorageObserver, filter);
}
private void buildData() {
// builds a list
}
}
Content of Manifest file:
<application android:persistent="true" android:icon="#drawable/icon"
android:label="#string/app_name" android:name="com.webgyani.android.MyApplication"
android:debuggable="true">
<activity android:name=".HomeTabActivity" android:launchMode="singleInstance"
android:stateNotNeeded="true" android:theme="#style/LightTabsTheme"
android:screenOrientation="landscape" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
This works fine when I install the app either using Eclipse or manually installing the apk onto the device. Once the app is installed things work fine, I mean the above onCreate() method gets called and service is also started normally, but if I reboot the device this time the onCreate() method does not get called(none of the log statements appear and also the services are not started). After some debugging I noticed that this only happens if I set my app as the default launcher/homescreen app and thereafter reboots the device, because once you set the app as the default launcher, Android should automatically launch your app as the homescreen after reboot. In my case the app is launched but that code is not executed.
I tried to use debugger but that didn't work because when I reboot the device the debugger gets disconnected and by the time USB debugging gets enabled my app is already started.
I even double checked the Logcat but didn't see any error. I thought of having a BOOT_COMPLETED intent to initialize that part, but that will require some code refactoring which I am not willing to do at this point of time unless there is a solution.
So I am curious to know that whether this is a standard behavior, or is there a known bug which causes this, because my assumption is the onCreate method of the Application will always get called whenever the app is started. I have tried whatever I could since morning, but nothing worked, couldn't pinpoint the issue, if any of you could shed some light into this then that would be highly appreciated.
Thanks
Well, finally I figured out the problem, and it was in my code itself. I initially suspected that the MyApplication's onCreate() method was not getting called, I had that assumption because I was not able to see any logs. To know whether the method is getting called or not, instead of using Log.i() I was also appending some additional log messages in an ArrayList and printing them later, this revealed that the methods were indeed getting called and even the Service was instantiating properly but the data or filelist is not being populated because the SDCard was not ready by that time. I am also pretty sure that the logs were not available on Logcat due to the fact that the USB debugger becomes ready after my app is started(as it's a homescreen app).
The actual problem becomes obvious when you see that my overridden MyApplication class implements a listener called ExternalStorageListener which basically extends BroadcastReceiver, I have created that class to receive SDCard related Intents for example ACTION_MEDIA_MOUNTED, ACTION_MEDIA_REMOVED to rebuild the data(file list). In my case the ExternalStorageListener class was not receiving the Intents because I forgot to add this filter.addDataScheme("file") in the registerExternalStorageObserver method above in the code sample.
I do agree that my question was based on a false assumption and the code example I posted it's kind of hard to figure out the actual issue. I am not sure what to do with the question whether to mark this as answer or leave it as it is.
I have written a few Android apps, and have always declared a starting Activity as the:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
It would be great for scoping some global methods, statics, shared prefs, etc if I could start my app using an Application that then calls the first Activity from it's onCreate() after setting up prefs, etc, but I haven't been able to find any examples of this design pattern... when I try this in code, I get a ClassCastException:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// do stuff (prefs, etc)
// start the initial Activity
Intent i = new Intent(this, InitialActivity.class);
startActivity(i);
}
}
InitialActivity.class is indeed an Activity that works fine if I set it to be MAIN, but trying to start it from MyApplication that is declared MAIN generates the error. Probably a very silly question, but am I tackling this all wrong?
Thanks,
Paul
You can fix this by using FLAG_ACTIVITY_NEW_TASK flag:
Intent intent = new Intent(this, ApplicationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
That's because you need to start new task when Activity is started outside of Activity context. But I strongly recommend to not start Activity from your Application's onCreate().
Android has 4 components: Activity, Service, ContentProvider and Broadcast.
When Android needs to activate one of this components from your application, it looks if there is already existing running process with your application. If not, then Android starts new process, initializes it, then it initializes your custom Application instance. And then it activates one of needed components.
Now, let's consider next scenario: your application declared content provider in AndroidManifest.xml, and Android just about to start your application so you can provide some data to another foreground application.
Content Provider request is sent
Your application wasn't running, and Android starts new process for it.
Your custom Application instance is created
Application.onCreate() is called.
You start an activity
Your Content Provider receives request
Somebody just wanted to connect to your content provider, but your application started an Activity instead. Same true for starting background Service and sometimes broadcast receivers.
And also consider if some other application's activity A wanted to started activity X from your application. But in onCreate() you started activity Y, and then X is also started by Android. Then user presses back. What should happen? Its tricky...
Starting activities from Application's onCreate may result in quite weird user experience. So don't do it.
UPDATE:
Because Android guarantees that Application will be created only once and before any other component, you can use next code to access your Application's single instance:
public class MyApplication extends Application
{
private static MyApplication s_instance;
public MyApplication()
{
s_instance = this;
}
public static MyApplication getApplication()
{
return s_instance;
}
}
Did you set it in you manifest activity tag for this intent you are starting (another one besides your main) ?
</activity>
<activity android:name=".InitialActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="com.package.INITACT" /> <--- this is only name by which you activity can be called.
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>