This Question i specific to Android and the use of a Base Activity that can be extended by all other Activities. In general w.r.t Java i understand the use and functioning of abstract classes. I my case i have a Base Activity with some common constants ,functions and implements some Interfaces. My Question is should it be abstract or can i leave it as a normal Activity. Is there a specific reason for it to be abstract.
//Standard BaseActivity
public abstract class BaseActivity extends Activity {
//common code
}
//Usage
public class MyActivity extends BaseActivity {
}
This also seems to work if i defined BaseActivity as follows
//Non Abstract Class
public class BaseActivity extends Activity {
}
Hence the question is there a specific reason to use abstract.
In both cases i dont define the BaseActivity in Manifest.
You can refer the following way for defining a BaseActivity.
It’s always been a good idea to make a baseActivity in android
project.
What, I am suggesting is to create an activity from android.app.Activity called baseActivity and make the 3 custom activity to extend from baseActivity.
For example,
public abstract class MyAppBaseActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
And your custom activity
public class MyCustomActivity extends MyAppBaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Notice that, MyAppBaseActivity is an abstract class. The reason is, we are not going to instantiate it. That’s why you don’t need to add the MyAppBaseActivity class in AndroidManifest.xml file.
Now the question is, why would you do that? Means, why you need to
make an baseActivity class and then make your other activities as a
subclass of it?
Well, here are few very generic reasons
1. You can avoid code duplication of you application wise common ui tasks. Suppose you want to show progressDialog in different activities. Just write code to show a progressDialog in your baseActivity and call that method from other activity.
2. Your application menu should be consistent across different application. For example, you have a settings screen. Option menu is containing the navigation to settings screen. You should display the settings throughout the application, means regardless of activity. User want to access the settings screen from anywhere in application. This feature can be easily achieved, but you have to override onCreateOptionsMenu in each of your activity or, you can override it once in your baseActivity.
Related
How can I implement "dispatchTouchEvent(...){}" on root of my android app instead of each of activities, because I want to get when my application get sleep or in pause state.
You could create a BaseActivity where you implement it and all your activities inherit from BaseActivity:
class BaseActivity extends AppCompatActivity {
dispatchTouchEvent() {...}
}
class MyActivity extends BaseActivity {
...
}
This kind of central handling would be possible if all your activities are extended from single activity in your project. Say, AppBaseActivity contains most general functionality & all others extend it. So, events can be traced down to this AppBaseActivity. I can't predict any other way to achieve the result you want to get.
I have a base activity from which I subclass several other activities.
Those other activities I do register in the manifest so I can use them from within my application.
However, Android inspection says, for my base activity, "Activity not registered in the manifest".
I see no reason to register the base activity as I never use it directly. However, maybe, I am missing something and the warning should not be ignored?
Why this warning anyway?
You'll only need to list activities that are entry points to your app in the manifest. That is, activities that are invoked with an Intent.
You should not have activities that are in fact not instantiable entry points. Make such activity classes abstract. This will also get rid of the lint warning.
You should make your BaseActivity as an Abstract class. No need to register such Activities in manifest, they are just simple java classes extending Activity class not an Activity of your application.
public abstract class BaseActivity extends Activity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
setContentView(getLayoutResourceId());
}
protected abstract int yourmethods();
}
public class Activity1 extends BaseActivity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
// do extra stuff on your resources, using findViewById on your layout_for_activity1
}
#Override
protected int yourmethod() {
//implemetation
}
}
Declare in the manifest only the activities that user can see during its experience. Usually these are called by intents. The others you should declare abstract.
I need to create a base class that extends Activity which does some common tasks in my application and extend my activities from it,in the following form:
public BaseActivity extends Activity{....}
public SubActivity extends BaseActivity{...}
in SubActivity I need to give values to some variables and UI components defined in BaseActivity, I may need to define a different layout for SubActivity according to some flag value, also(in SubActivity ) I want to execute asyncTask that is defined in BaseActivity.
is this possible? if yes, is there any tutorial that may help?
thank you in advance
What exactly are you trying to achieve? Having two different activities with a common ui, except for some variables or parts of the layout?
In this case, I suggest having a base abstract activity, and two concrete inherited subclasses. You define all the common behaviour in the base activity, and have abstract methods for the differences, which you then override in your actual implementations.
For example, for two activities with different layout resources:
public abstract class BaseActivity extends Activity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
setContentView(getLayoutResourceId());
}
protected abstract int getLayoutResourceId();
}
public class Activity1 extends BaseActivity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
// do extra stuff on your resources, using findViewById on your layout_for_activity1
}
#Override
protected int getLayoutResourceId() {
return R.layout.layout_for_activity1;
}
}
You can have a lot more abstract methods, for every bit you want specific to your subclasses.
Doing that is, in my opinion, a lot better than having a concrete subclass to a concrete superclass: that can lead to many problems and is usually difficult to debug.
This question already has very good answers.
However. my answer is for those people who are looking for some working example.
Here is the full working -> CODE
We are not doing anything new here, it is just like any other inheritance scenario (You want some common behavior at multiple places but you want to write that behavior only once).
ADVANTAGE:
It does provide better code readability, maintainability and blah blah. But are not after these -ibility, They won't matter to you if your brain runs like a gazelle.
We are after the real power of inheritance “CONTROL”. (That’s what happens in real life too. Parent controlling child :) ) .
In my example, I have two Activities MainActivity and OtherActivity.
Both Activities has a different layout but I want both of them to start with some animation or some welcome message.
Our first task is to find out the common behavior.
here -> Start Activity with animation.
We have found the common “thing”, now we will write that behavior in BaseClass (AnimationActivity).
MainActivity and OtherActivity will inherit AnimationActivity.
So the code would look like `
BaseActivity
AnimationActivity {
startAnimation()
{
....
}
}
Child Activities
MainActivity extends AnimationActivity{
}
OtherActivity extends AnimationActivity{
}
This design approach provides a lot of Control and Flexibility (POWER OF MODIFIER).
1) CONTROL: Keep animation method inside onCreate()
When you decide that Activities should be started with Animation.
Keep your method inside onCreate(Bundle bundle) method. Now just by changing the modifier, you can control the child Activities.
If you keep modifier as
final: Child activities will start with parent Animation.
abstract: Child activities will have to give their own animation.
no modifier: Child activities can have their own animation by overriding animation method, Otherwise the child will have parent animation.
2)Flexibility: Don't keep animation method inside onCreate()
You can provide child activities flexibility by not keeping animation method inside onCreate(Bundle bundle).
Now activities can have the flexibility to have parent Animation or their own animation or no animation at all.
Hope it helps.
Happy learning.
`
Yes you can, you should just keep in mind the basic inheritance rules. You will inherit the inner AsyncTask activity and the properties defined in the BaseActivity if you make them protected instead of private. From what I see now I think you should make BaseActivity an abstract class, as only instances of subActivities will be really used.
You should just start and try it, it'll come and work easier than you think. If you stumble upon any problems, just ask.
I have found an easier way to #Guillaume's solution. Set ContentView only once in your BaseActivity and do not set it in the activities that extend it:
public abstract class BaseActivity extends Activity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
setContentView(activity_main);
}
}
public class Activity1 extends BaseActivity {
#Override
public void onCreate(bundle) {
super.onCreate(bundle);
// setContentView(activity_activity1) // Do NOT call this.
}
}
Is there a way to intercept whenever the Application creates a new Activity instance? I'm only interested in Activities belonging to the Application process not all Activities on the phone. Is there some way to do this? Is the Application class involved in doing this in some way? What methods can I override to get at the Activity instance after it's been created?
Ok, just an idea - in your app you can create a base activity class so all the rest of activities are subclassed from that base activity. Then in the onCreate() callback you may notify some listener instance about the fact of a new app activity instance creation:
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// put the code to notify a listener here
}
}
public class YourWorkingActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
}
If you use a ListActivity (that is common for an average Android app), then you should also create a similar BaseListActivity for it.
Most likely the best candidate for a listener would be an Application subclass since it is guaranteed by the OS that is will be created before any Activity will be instantiated.
Warning: you should avoid keeping a strong reference to an Activity in the listener since it will create a memory leak when the OS will try to kill that Activity (as a part of the Activity or Process life-cycle). Probably use WeakReference for this.
I would like to run a piece of code every time any activity or service is started. In this piece of code, I might do things such as set the default uncaught exception handler and manage log levels.
The problem is that I have an activity which starts with the user clicking the application icon. I have another which starts if a certain intent is broadcasted, possibly from another app and possibly called before the user click the launch icon. Same goes for services.
I need to guarantee that a certain piece of code will be run while keeping the code clean; that is to say, without having to manually add that snippet of code to every activity and service class that I have.
Could you not extend the basic Activity class for Android like this:
public class MyClass extends Activity {
public void onCreate(Bundle bundle) {
//Add custom code here
}
}
Then have all of your actual "Activity"'s in your application extend the custom class?
public class MyInterfaceClass extends MyClass {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
//Other code here
}
}
That way all your custom code will be called when the Activity starts up.
For an application called Wibble...
public class Wibble extends Application {
protected static void DoSomething()
{
// Do your common code here
}
}
Then extend Activity...
public class WibbleActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Wibble.DoSomething();
}
}
Then derive all activity classes from WibbleActivity...
public class Whatever extends WibbleActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// WibbleActivity calls Wibble.DoSomething()
// so the 'Whatever' class doesn't have to.
}
}
Any Activity derived from WibbleActivity will run Wibble.DoSomething() implicitly.
If you want Services in the mix I can't help - I'm an Android 'rookie' and haven't got on to Services yet but I suspect extending your own app-level Service class might work in the same way.
You could extend Application and do it in its onCreate() method.
You have two choices
A) You can manually add the code - it might be only two lines importing and instantiating something from a source file you copy in unmodified - to every separate component that you write. It will only be in your projects, not in other people's unless they do it too.
B) You can, after no small difficulty, learn to make your own custom version of android that automatically does this each time it starts up a suitable component, and install this customized version on developer phones or hacked consumer phones.
"started" is ambiguous - what are you referring to? onCreate? onResume?
In any case, your best bet is to have a separate class with a static method that does the code you are talking about, and you call that in every single onCreate (or onResume, whichever you need) of each one of your activities.
That, or you create your own Activity subclass and derive all your activites from it, and override onCreate (or onResume). All your onCreate/onResume implementations are required to call the superclass' implementation, so you're guaranteed to have your code caled.