I am fairly new in android and Java and this question might seem a little bit a naive question ,
I am trying to write a method called getDispalay() , this will be a public with no retuen.
I will print a message saying I am in the getDisplay method .
In java it is very simple , It will be called in main method , But I do not know how i can use main method in activity class ? I mean how can I write a method and call it as I need it ?
Thanks
Go through this article
As you said in java we call the function in main method .
In android if java class extends activity you can call the method in Any of the life cycle event of activity , It depends on your need . For example if you want to call method when you enter into activity follow this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)//To set up ui for activity
getDispalay();
}
public void getDispalay(){
//your actions
}
What you really need to do is understand the activity lifecycle:
Once you have read through that then you will know how your Android app runs and what states and stages it transitions through.
You should read the documentation about Activity Lifecycle.
The onCreate() method would be comparable to main().
Related
I am new to both Android and Java (as well as OOP), so forgive me if this is super noobish. In going through the Android tutorial on a first app, the following code is written:
#Override
protected void onCreate(Bundle savedInstanceState){...}
I have read that #Override is overriding the default onCreate call and that, if you don't override, you can't specify which activity to use. That's all well and good, but in the interest of understanding, what exactly is the default activity if activity_main is not in the case that you don't override onCreate?
I think what you are asking is what does the base class onCreate method do, and what happens if you don't override it. You can look at the source code for Activity here, or the AppCompatActivity here to look at what is in the base class. Notice that a typical implementation in an app looks like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// other custom setup code for your activity
}
That first call to super.onCreate still calls the base class onCreate method (the one you are overriding), so you're not replacing what's in the base class, but adding your customizations specific to the Activity you are creating. That call to super does a number of Activity setup things that you always have to do. It doesn't associate the activity with any layout file (which is done by the setContentView call), so it wouldn't display anything from your xml files without you adding the setContentView call. There is no default xml layout file it would use.
I believe you mean the default Activity layout?
If you don't set one in onCreate with setContentView I think you simply won't have one.
I am having trouble applying the concept of inheritance to Android Activities - eg.
ActivityA extends Activity and
ActivityB extends ActivityA , then if I launch with ActivityB then onCreate() method for both Activities (A then B) is called .
My question is, in typical Java , onCreate from ActvityA should be over-ridden - but onCreate is rather behaving as a constructor even though its a function. How does inheritance work in Android, esp. wrt other functions like onPause(),onResume etc. ?
EDIT: I also noticed that ActivityA may have many abstract methods called in its onCreate() whose definitions are provided in ActivityB. How does this work ?
If you have your base Activity and then extend it like so Activity -> Activity A it means that when your onCreate of Activity A is called and you call super.onCreate(); then the onCreate() method of the original Activity is also called.
If you then extend Activity A into Activity B the calls work like so...
Activity B.onCreate() - super.onCreate();-->Activity A.onCreate() - super.onCreate()-->Activity.onCreate().
Its not a constructor, its a method thats called to create the Activities. If you then extend them from other Activities its superclass is going to be called via its super method. It doesn't mean that the Activities you have inherited from are going to be created too. Activity B will be your created Activity.
EDIT: This page on the Android Developer website is very useful as it visually explains the Android Activity lifecycle.
Yes as a typical java function onCreate should have been inherited but it doens't get : why? - because it's not just a method, it's a life cycle stage.
AFAIK, Activity is not just a java class but it's a special type of a JAVA Class which has it's own life cycle and Life Cycle stages are meant to be called each and every time you use that class/activity even if you have declared or not those methods onCreate(), onPause() etc gets called for sure.
So every time the base activity will get created and destroyed. That's it's nature.
If you have problem with that you can try using Abstract classes, Interfaces and any other public class to have common code inherited in your all activities.
How does Inheritance work in Android?
There nothing special about Android. It works exactly as it should.
Example?
Lets create a BaseActivity which listens to a BroadcastReceiver (SCAN_RESULTS_AVAILABLE).
So common functions are,
Register a BroadcastReceiver in onCreate()
Unregister a BroadcastReceiver in onDestroy()
BaseClass:
public class BaseActivity extends AppCompatActivity{
private WifiScanReceiver wifiScanReceiver;
#Override
public void onCreate(Bundle sis)
{
super.onCreate(sis);
// Don't call setContentView() because no layout is needed
}
#Override
public void onDestroy(){
super.onDestroy();
unregisterReceiver(wifiScanReceiver);
}
private void registerMyReceiver(){
wifiScanReceiver = new WifiScanReceiver();
registerReceiver(wifiScanReceiver, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
manager.startScan();
}
}
Child class:
public class BlahBlahActivity extends BaseActivity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState); // this will call BaseActvity method which will call AppcompatActivty method
setContentView(R.layout.yourlayout);
}
}
I have a one notification service which fires at every 5 seconds and get the data and parse it and then display it..
But this mechanism works only for the home screen of the app.
I want this to be done in every screen of the app.For that should i write the same code in every activity of the project ? It is very tedious job . I want to make it generalize ..
How to do that ?? any ideas??
you can make BasicActivity and have method in that Activity and call that method inside onCreate();
now extend every Activity in your project from your BasicActivity
If you are talking push notification service, this idea seems to problematic. tell us more what are you exactly trying to do.
you do something like this in some utility class
public static void showNotifction(Activity a)
{
//notify
}
and over this if you have any call back methods.. Then create an interface with those methods and implement them in all those Activities and you can do this..
public static void showNotifction(CommoInterface a)
{
if(a insatncof Activity){
//notify
a.callBack(); // callBack is a method in the interface..
}
}
I have a set of commands that I want my app to run when it's restarted, regardless of what activity it's on. I know I need to put an onRestart() into every one.
Since it's the same set of commands regardless of what activity it's on, is there a way I could have them all refer to a single function for that? It seems like that would be better then having to copy paste the commands into each onRestart() handler. It will be a lot less work if I need to change the set of commands too.
You have a couple of options, depending on the code.
You can put it in a helper class as a static function: public static void doWork() { .. } This should work, unless whatever you are doing depends on being in the activity. You can generally just pass it what it needs though, like the Context.
Or, you could extend Activity with your own class, MyActivity and place the work in that onResume. Then extend MyActivity for each of your real activities. They will now automatically do that work when you call super.onResume(). This works well as long as you really want to do the same thing in every activity, and don't use a lot of specialized activities like ListActivity.
Edit:
public class MyHelper {
public static void doWork() {
// do your work here
}
}
public class MyActivity extends Activity {
public void onResume() {
super.onResume();
MyHelper.doWork();
}
}
A search for "static method" will provide more details.
Derive all your activities from a single class (something like ActivityBase) that, in turn derives from system-provided Activity. Then implement onRestart() in ActivityBase.
Is it your application that is restarting from scratch? Or just your activities that are restarting/resuming?
The Application class has an onCreate() method, and you can extend Application in your app to override its behavior. Just remember to change the name of the application in AndroidManifest.xml so it picks up your custom Application class when starting. This code would run before any activities start up. But it won't run every time an activity is stopped and restarted. If that's what you need, this won't do it.
You could also implement a singleton class that contains an initialize() method, or restart() method. You simply call it from onRestart() in each activity you want it in. It sounds like this special code ought to be localized away from your activities so I don't think I'd recommend extending Activity to put the code there.
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.