Creating Global Functions In Android
Solution 1:
Create Class like this and add your functions here :
package com.mytest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
publicclassMyGlobals{
Context mContext;
// constructorpublicMyGlobals(Context context){
this.mContext = context;
}
public String getUserName(){
return"test";
}
publicbooleanisNetworkConnected() {
ConnectivityManagercm= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfoni= cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.returnfalse;
} elsereturntrue;
}
}
Then declare instance in your activity :
MyGlobals myGlog;
Then initialize and use methods from that global class :
myGlog = newMyGlobals(getApplicationContext());
Stringusername= myGlog.getUserName();
booleaninConnected= myGlog.isNetworkConnected();
Permission required in your Manifest file :
<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE" /><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" />Thanks.
Solution 2:
Create Utility class like this:
publicfinalclassAppUtils {
privateAppUtils() {
}
@SuppressLint("NewApi")publicstaticvoidsetTabColor(TabHost tabHost) {
intmax= tabHost.getTabWidget().getChildCount();
for (inti=0; i < max; i++) {
Viewview= tabHost.getTabWidget().getChildAt(i);
TextViewtv= (TextView) view.findViewById(android.R.id.title);
tv.setTextColor(view.isSelected() ? Color.parseColor("#ED8800") : Color.GRAY);
view.setBackgroundResource(R.color.black);
}
}
}
Now, from any class of Android application, you can function of Apputils like this:
AppUtils.setTabColor(tabHost);
Solution 3:
This may not be the best way to do this and there would be others who might suggest some better alternatives, but this is how I would do.
Create a class with all the functions and save it as maybe Utility.java.
Use an object of the Utility class throughout the code where ever you need to call any of the functions.
UtilitymyUtilObj=newUtility();
myUtilObj.checkInternet();
Or maybe make the functions static and you can simply use Utility.checkInternet() where ever you need to call it.
Solution 4:
Just create public class with static methods, something like this ...
package com.example.test1;
publicclassGlobalMethod {
publicstatic String getHelloWorld() {
return"Hello, World!";
}
publicstaticintgetAppleCount() {
return45;
}
}
Now from anywhere you can call the methods ...
GlobalMethod.getHelloWorld();
GlobalMethod.getAppleCount();
There are many ways to do though, check it out other answers. Hope this is helpful.
Solution 5:
You can create a utility class, which has a set of static methods (given that such a class doesn't hold any real state of its own). Now these static methods can be called from different parts of the application.
Post a Comment for "Creating Global Functions In Android"