Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating global functions in android

Tags:

java

android

What i want to do is create a java file that has various functions and I would like to use it across the whole project. For example check Internet Connection. Then I would like to call that function on each activity. Does anyone know how to do that?

like image 752
Luke Batley Avatar asked Jan 23 '13 16:01

Luke Batley


2 Answers

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.

like image 131
Pratik Sharma Avatar answered Oct 07 '22 22:10

Pratik Sharma


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);
like image 22
Zoombie Avatar answered Oct 07 '22 20:10

Zoombie