Android Application vs Activity -
i have written few android apps, , have declared starting activity
the:
<intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter>
it great scoping global methods, statics, shared prefs, etc if start app using application
calls first activity
it's oncreate()
after setting prefs, etc, haven't been able find examples of design pattern... when try in code, classcastexception
:
public class myapplication extends application { @override public void oncreate() { super.oncreate(); // stuff (prefs, etc) // start initial activity intent = new intent(this, initialactivity.class); startactivity(i); } }
initialactivity.class
indeed activity
works fine if set main
, trying start myapplication
declared main
generates error. silly question, tackling wrong?
thanks,
paul
you can fix 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 need start new task when activity started outside of activity context. recommend not start activity application's oncreate()
.
android has 4 components: activity, service, contentprovider , broadcast.
when android needs activate 1 of components application, looks if there existing running process application. if not, android starts new process, initializes it, initializes custom application instance. , activates 1 of needed components.
now, let's consider next scenario: application declared content provider in androidmanifest.xml
, , android start application can provide data foreground application.
- content provider request sent
- your application wasn't running, , android starts new process it.
- your custom application instance created
application.oncreate()
called.- you start activity
- your content provider receives request
somebody wanted connect content provider, application started activity instead. same true starting background service , broadcast receivers.
and consider if other application's activity wanted started activity x application. in oncreate()
started activity y, , x started android. user presses back. should happen? tricky...
starting activities application
's oncreate
may result in quite weird user experience. don't it.
update: because android guarantees application created once , before other component, can use next code access 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; } }
Comments
Post a Comment