Creating global functions in android

What I want to do is create a java file with various functions, and I would like to use it in the whole project. For example, check your internet connection. Then I would like to name this function for each type of activity. Does anyone know how to do this?

+5
source share
5 answers

Create the class as follows 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 an instance in your activity:

MyGlobals myGlog;

Then initialize and use the methods from this global class:

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

boolean inConnected = myGlog.isNetworkConnected();

Permission required in manifest file:

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

Thank.

+11
source

Create the Utility class as follows:

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 Android application, you can function Apputils as follows:

AppUtils.setTabColor(tabHost);
+3

, , , I.

Utility.java.

Utility , .

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

, , static, Utility.checkInternet(), .

+1

, (, ). .

0

public static, - ...

package com.example.test1;

public class GlobalMethod {

    public static String getHelloWorld() {
        return "Hello, World!";
    }

    public static int getAppleCount() {
        return 45;
    }
}

...

GlobalMethod.getHelloWorld();
GlobalMethod.getAppleCount();

There are many ways to do, though, check out the other answers. Hope this will be helpful.

0
source

All Articles