Category Archives: Java

Android_Robot_200

Android Context in non-activity Class – The Secret of ContextWrapper

Android Context in non-activity Class – The Secret of ContextWrapper

Android Context in non-activity Class

One of most frustrating issues I had to figure out when I’ve started to develop for Android was the Context.

Why there are several kind of Context? and more important – How can I call to system API method from a Class when all the important functions are available only from a Context class??

The problem

Let’s take this function inside activity for example (test for AirPlane Mode),
Where isAirPlaneModeOn() is using the getContentResolver() which is Context.method:

public class MyActivity extends Activity {
 
   ...
 
   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
    }
 
}

Or inside a service:

public class MyService extends Service {
 
   ...
 
   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
 
}

P.S: The isAirplaneModeOn() function is using depreceated method (pre API 17) just for the purpose of simple example and backward compatibility.

Now… lets say you want to create some other class, and move the function to that class:

import android.provider.Settings;

public class MyOtherClass {
   ...
   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(<span style="text-decoration: underline;">getContentResolver</span>(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

HEY?!!? Why Eclipse telling me: The method getContentResolver() is undefined for the type MyOtherClass

????? ….. Because getContentResolver() is a context method – Soon you realize you must have access to Context.. so What the solution?

 

Some solutions

I’ve read a lot about context(s). Maybe, most of the valuable stuff out there in the internet…

Some are saying to pass the context to the class and save a reference to that context like:

class YourNonContextClass {
   private Context context;

   public YourNonContextClass(Context context){
      this.context=context;
   }

   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(context.getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

Some are saying to pass the context to your static function like:

public class MyOtherClass { 
   public static boolean isAirplaneModeOn(Context context) {
      return Settings.System.getInt(context.getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

Both solutions works. Both have their Pros and Cons. both require you to alter the code inside the function.

 

Solution – The Secret of ContextWrapper

Finally … After a fashion… With lot of experimentation, I’ve found a great solution that I really like! :

CONTEXTWRAPPER!

So What is ContextWrapper?

Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.

In other simple words: It’s a class that inherits another Context.

 

So, How to use the ContextWrapper?

Let’s talk about the function we discussed above and create a ContextWrapper class for it:

public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
      super(base);
   }

   public boolean isAirplaneModeOn() {
      return Settings.System.getInt(getContentResolver(),
         Settings.System.AIRPLANE_MODE_ON, 0) != 0;
   }
}

Note that nothing need to be changed in the isAirplaneModeOn() function as the class itself inherits the wrapper you’ve called from (Activity, Service, IntentService, etc).

To call the function just use:

boolean isAir = (new MyContextWrapper(this)).isAirplaneModeOn();

Where ‘this’ could be any context you’d like to. applicationContext, Service or Activity.

 

That’s it.  Easy haa!

And choose what fits you best…

 

Development Specialist, Artist and Activist
Personal Website
android

Android Get Mobile IP Address code example

Android Get Mobile IP Address

Android Get Mobile IP Address Code Example

Android Get Mobile IP Address :

Getting the android IP address for Wi-Fi connection using the API is very simple:

/**
 * Get the IP of current Wi-Fi connection
 * @return IP as string
 */
private String getIP() {
 try {
   WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ipAddress = wifiInfo.getIpAddress();
   return String.format(Locale.getDefault(), "%d.%d.%d.%d",
   (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
   (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
 } catch (Exception ex) {
   Log.e(TAG, ex.getMessage());
   return null;
 }
}

But what if you need to get the Mobile connection IP?

The answer is to check the NetWorkInterface like this:

/** Get IP For mobile */
public static String getMobileIP() {
  try {
    for (Enumeration<NetworkInterface> en = NetworkInterface
    .getNetworkInterfaces(); en.hasMoreElements();) {
       NetworkInterface intf = (NetworkInterface) en.nextElement();
       for (Enumeration<InetAddress> enumIpAddr = intf
          .getInetAddresses(); enumIpAddr.hasMoreElements();) {
          InetAddress inetAddress = enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress()) {
             String ipaddress = inetAddress .getHostAddress().toString();
             return ipaddress;
          }
       }
    }
  } catch (SocketException ex) {
     Log.e(TAG, "Exception in Get IP Address: " + ex.toString());
  }
  return null;
}

And if you want to get the IP as IPV4 just replace the line:

          if (!inetAddress.isLoopbackAddress()) {

With:

 if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
Development Specialist, Artist and Activist
Personal Website
android

Android preference multiple dependency with CheckBoxPreference

Android preference multiple dependency

Android preference multiple dependency is not out-of-the-box feature until api level 14 introduced us with SwitchPreference (extends TwoStatePreference) to implement such feature. the old CheckBoxPreference can’t do that.

 

If your app is designed for newer systems only, (min-api equal or higher than 14) that won’t be a problem for you – because you can use the new SwitchPreference element to get at least 2 states, but if your app designed to work with older api support, or more than 2 dependencies on one element – you need another method.

Note: you can always implement both ways! use the ‘/xml-v14‘ directory to create multiple version of your XML, better with include, one for API 14 with SwitchPreference, and one for the old API’s with the following solution.

Continue reading

Development Specialist, Artist and Activist
Personal Website
javalogo

How to disable java in all browsers at once

Overview

Several major companies have been hacked lately. Security advice for web users last week from the US Department of Homeland Security encouraging to disable java on browsers. Disable java in each browser takes time. You will learn how to disable java for all at once. and also for each browser if needed.

Continue reading

Development Specialist, Artist and Activist
Personal Website