Is there any global activity on Android such that I put my code in that one activity, and it affects all activities in my project? This occurs to me because the same code is
You can create a class that extends Activity
and then extend the CustomActivity
to all the Activity
Class like this.
public abstract class CustomActivity extends Activity{
public abstract void initComponents(); // you can create a abstract method
public abstract void addListner(); // you can create a abstract method
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
// your stuff here....
}
return true;
}
}
Now you can extend
this class
where you want to extend
any class with Activity
.
Take your first main activity write code there, and simply after that extend all the other activity with this activity.....e.g. MainActivity is your first and main activity then write this code there, and after that simply take an activity say it First then extend it with MainActivity rather than Activity...!! and That's it..........
I would suggest extending activity as @Lalit Poptani suggested. Since that is been said i could provide an alternative way for this to work.
You can create an interface that you implement in your activity including public boolean onKeyDown(int keyCode, KeyEvent event) (just to keep you a reminder you have to implement the code to your activity)
Create a global (static) class/function that performs the onKeyDown operations.
public class ButtonHandler{
public static boolean handleButton(Context context,int keyCode, KeyEvent event){
..... your code here
}
}
and just call return ButtonHandler.handleButton(getApplicationContext(),keycode,event)
to your onKeyDown
methods.
But still .. overriding activity is the best way to go. If for some reason you don't want to extend this is the way to go