creating global functions in android

Create Class like this and add your functions here :

package com.mytest;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class MyGlobals{
    Context mContext;

    // constructor
    public MyGlobals(Context context){
        this.mContext = context;
    }

    public String getUserName(){
        return "test";
    }

    public boolean isNetworkConnected() {
          ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo ni = cm.getActiveNetworkInfo();
          if (ni == null) {
           // There are no active networks.
           return false;
          } else
           return true;
    }
}

Then declare instance in your activity :

MyGlobals myGlog;

Then initialize and use methods from that global class :

myGlog = new MyGlobals(getApplicationContext());
String username = myGlog.getUserName();

boolean inConnected = myGlog.isNetworkConnected();

Permission required in your Manifest file :

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Thanks.


Create Utility class like this:

public final class AppUtils {

    private AppUtils() {
    }

@SuppressLint("NewApi")
    public static void setTabColor(TabHost tabHost) {
        int max = tabHost.getTabWidget().getChildCount();
        for (int i = 0; i < max; i++) {
            View view = tabHost.getTabWidget().getChildAt(i);
                    TextView tv = (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);

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.

Utility myUtilObj = new Utility();
myUtilObj.checkInternet();

Or maybe make the functions static and you can simply use Utility.checkInternet() where ever you need to call it.

Tags:

Java

Android