When does Application's onCreate() method get called? - android-activity

In my Android application, I have a DefaultApplication class which extends android.app.Application, and in its onCreate() I bind some services which will be used by my other Activities in this app.
Also I have a BroadcastReceiver which listens and receives C2DM Messages. When this receiver receives a message when the application is not running, it will fire a dialog which shows the upcoming message and it will start an Activity of my application.
My question is, when I start an activity without any interaction with DefaultApplication, will my DefaultApplication's onCreate() get called because an Activity of that application has started?
Here are the definition and Manifest of my DefaultApplication:
public class DefaultApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
doBindService();
}
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(DefaultApplication.this, SocketService.class),
socketServiceConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(socketServiceConnection);
mIsBound = false;
}
}
}
Manifest looks like this:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="com.mypackage.DefaultApplication"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:debuggable="true">
<service android:name="com.mypackage.services.SocketService"></service>
<activity android:name="TestActivity"
android:screenOrientation="landscape"></activity>
</application>

Only the first time.
When Activity is started and application is not loaded, then both onCreate() methods will be called.
But for subsequent starts of Activity, the onCreate() of application will not be called.

You can find an official answer when onCreate is called here.
Called when the application is starting, before any activity, service,
or receiver objects (excluding content providers) have been created.
Implementations should be as quick as possible (for example using lazy
initialization of state) since the time spent in this function
directly impacts the performance of starting the first activity,
service, or receiver in a process. If you override this method, be
sure to call super.onCreate().

Note that if any service is defined to run in other process e.g. with android:process= then Application's onCreate() will be called again for that process.
For example see Android Application class method onCreate being called multiple times

Related

How to get Preloaded Actor state in Service Fabric

I am developing an application on Azure Service fabric. Its a simple User TODO application. I created TodoActor to add User TODO. It simply adds the User TODO using StateManager. I am aware that the StateManager will store the State in disk memory and not in any database.
But before starting the Application, I want that user should have preloaded Todos for them. Is there any way to have preloaded States for actor?
Is there any way to have this data in Database?
Actors are created when they are used. So for example, when it is called, or when a reminder triggers. If an Actor was never used before, it doesn't exist yet, so there is no way to pre-load state.
What you can do is pre-load data just-in-time when the Actor is created:
protected override async Task OnAactivateAsync()
{
if(!await StateManager.ContainsStateAsync("ToDoState"))
{
await this.StateManager.TryAddStateAsync<List<string>>("ToDoState", new List<string>{});
}
}

Is using registerReceiver on the application class cosidered a good, known practice?

Background
On Android, there are 2 possible ways to listen to system events via BroadcastReceivers :
statically, via the manifest
programmatically, via the code.
Since some projects contain a lot of activities, services, and "manager"-classes , it could be useful to have a single BroadcastReceiver that will notify all of its listeners on the app about what has happened, instead of having multiple BroadcastReceivers being used (and their code handling).
An example of such a BroadcastReceiver, is the one that listens to the connectivity changes:
#Override
public void onCreate() {
super.onCreate();
...
registerReceiver(new ConnectivityChangedBroadcastReceiver(), new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
...
}
The question
The purpose is to listen to the events while the app is "alive" (by services and/or activities) .
Using the manifest would miss this purpose, as it will wake the app each time the event occurs, even if the app doesn't need it.
Thing is, unregistering doesn't occur, and maybe it causes the OS treat the app in a different way because of it.
Does having a call to "registerReceiver" on the class that extends from Application is a good known practice?
Does it have any side effects and things to know about when using it?
Is there any alternative to this?
I just want to be sure it's considered safe to use.
we can't really know what is good or better for you.
I advise you to learn more about the difference between the registration ways of the receiver:
1/ in the manifest :
the handler of the receiver will be triggered each time that the correspondent event comes. Example: the messenger of facebook is lunched every time that you have internet connection to show you your notifications... or other applications are lunched when you connect to propose updates ...
in other words, the receiver is always registered.
2/ in a service or an activity or an application :
the receiver will be unregistered when the context of where it is registered is killed.
in other words, it depends totally of the context where it is registred , and you are obliged to unregister it somewhere in the code. exemple : one activity is waiting that a service ( which is doing something in the background) sends an alert to update something , then you can register the receiver in your onResume() and unregester it in your onPause().
Conclusion : It depends only in the life-cycle requirement of the receiver.
see also Broadcast Receiver Register in Manifest vs. Activity
Main difference between Manifest and Programmatic registering of BroadcastReceiver

Google In-App Billing causing Exception

In one of my Android apps, I'm trying to implement a simple grab of the inventory from Google's In-App billing, but it keeps giving me errors at the line of
mHelper.queryInventoryAsync(mGotInventoryListener);
with the message that
IabHelper is not setup. Can't perform operation: queryInventory
Here is all the IabHelper code.
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
}
});
//check to see if ads have been removed(bought)
IabHelper.QueryInventoryFinishedListener mGotInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// handle error here
}
else {
// does the user have the premium upgrade?
if(inventory.hasPurchase(REMOVE_ADS)) removeAdsPurchased = true;
// update UI accordingly
}
}
};
mHelper.queryInventoryAsync(mGotInventoryListener);
The short answer is that your queryInventoryAsync() call should be made from inside your onIabSetupFinished() method. This is an asynchronous call, and so you cannot just proceed with using the IabHelper instance until that callback has been invoked to tell you that the helper's communication with the billing service has been established. The way your code is presently written, you have a race condition, and your queryInventoryAsync() call is going to win that race and attempt to use the IabHelper object before it has been set up, which is the cause of your problem.
Also, any further code in UI handlers that relies upon this object (e.g., the handler for a button that initiates a purchase) should test for a fully set-up IabHelper object, and should not allow the user to use that UI element until the IabHelper instance created in onCreate() has successfully completed setup. The easiest way to handle this situation is to simply disable such UI elements until the setup callback has been invoked to indicate that setup has completed successfully.
That is the easy part. The more serious problems occur when you have actions that occur immediately after your onCreate() method runs (i.e., not under the control of the user), that require the use of a fully set-up IabHelper instance. This typically occurs as a result of activity lifecycle calls - specifically, onResume() (if there is something requiring an IabHelper instance that must be done each time your app comes to the foreground, and not just when onCreate() is called) and, most notably, in onActivityResult() (which is invoked when the user completes or aborts an interaction with the billing interface - e.g., as part of making an in-app payment).
The problem is that your app may be stopped by the OS (e.g., to make room for the billing interface itself when the user initiates a purchase), causing your IabHelper instance to be destroyed along with your app, and that instance will have to be regenerated when your onCreate() is next invoked, and setup will once again be initiated in onCreate(), and once again you will need to wait for setup to complete before doing anything else with that object.
One notable situation where this can occur is during the user's interaction with the billing interface as part of the purchase process. The result of that interaction will be communicated to your app via onActivityResult(), which itself needs to use a fully set-up IabHelper object, and so if your app gets flushed from memory while the user is interacting with the billing service to make (or cancel) a purchase, then onActivityResult() will have to wait for the IabHelper instance to get set up again (after it is re-created in onCreate() before it can use it.
One way to handle this would be to set up and post to a queue of pending actions requiring an IabHelper instance, that your onResume() and/or onActivityResult() code adds to, and have that queue processed by your onIabSetupFinished() method once the IabHelper setup (initiated by onCreate()) has completed.
It's not trivial. And last time I checked, the TrivialDrive sample app did not handle the above situation.
The best way to test this kind of use case is to use the developer option "Don't Keep Activities," which causes your app to be destroyed each time the user leaves it, to simulate what the OS will do when it needs to reclaim memory, so that you can make sure your app works under those conditions.
Great stuff from Carl. I "think" I am seeing a similar thing, though my app is crashing via:
java.lang.IllegalStateException: IabHelper was disposed of, so it cannot be used.
And it my case, rotating the device one way, then immediately back to the original orientation SOMETIMES causes this crash. Seems that there's a "window" of time where this crash "might" happen (due to the asynchronous nature of IAB like Carl explained).
My fix
My "fix" was to make mHelper static, and only instantiate it if (mHelper == null), and NOT destroy it in the activity's onDestroy() method. This way, once it's setup, it sticks around, and there's no need to worry about asynchronous operations (causes by device orientation) anymore.
Not sure if this is the right fix or not, but thought I'd mention it in case it help others.
Simply make the checkNotDisposed() method synchronised and the problem goes away. This is because it is sometimes called in a separate thread and does not always have the latest value of mDisposed, which may have been set in the main thread:
private synchronized void checkNotDisposed()

How to call long running web services in c#?

I have one web service method it is taking long time to run. i want to make it asynchronous
and web service client should not wait for web method to complete. How i could implement this on c#.
//Web Method
[WebMethod]
public void StartProcess()
{
//long running method
}
//Web Client
webService.StartProcess();
Generate your service reference or edit it by choosing async option in VS, now the generation process will create two calls and one will be yourMethodAsync that you can call. You can also setup a callback this way.
Also you can use parallel tasks in C# to put a call on a background thread. I prefer to generate the async methods since it is cleaner.
here is a post that will help

Android: How to run service when application is visible?

I want a service to run in the background whenever one of a number of the activities in my application is visible.
I'm currently binding to it in a sub-class of Application, like so:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
bindService(new Intent(this, MyService.class), mServiceConnection, BIND_AUTO_CREATE);
}
}
However, there's no corresponding onDestroy method in which to unbind the service. When when the last activity closes, the service continues to run indefinitely.
Is this OK as it is? Should I just allow the OS to shut the service down when low on memory?
Alternatively, is there a way to do this on a per-activity basis?
It could be very easily done. Bind the service to the foreground activities. As long as the activities are active Android will keep the service going.
When all the activities are unbound the service will die automatically. (services called by onbind will die automatically when all the bind activities are gone). Only when you use onCreate to create a service you should worry about ondestroy.