Tag 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
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
wordpress-logo-stacked-rgb

Must have best FREE WordPress plugins 2012

FREE WordPress plugins 2012

To summarize the year 2012 I have compiled a list of must have WordPress plugins:

Continue reading

Development Specialist, Artist and Activist
Personal Website

Background processing with IntentService class

This article explain the usage of IntentService class in android SDK to perform background processing to offload tasks from an application’s main thread (Your activity).
when IntentService jobs done, the results are sent back to the activity.

Continue reading

Development Specialist, Artist and Activist
Personal Website
JSON

Transfer data from PHP to Android (JSON) – Part 1

You may reach a point where you need to transfer data from a server (web-service) to a an android client. although, there are many ways to achieve that goal, one of the simplest is using JSON. JSON is better then XML in terms of small bandwidth footprint. it has a lot of libraries for every available platform, so it makes the best solution for server-client communication.

Continue reading

Development Specialist, Artist and Activist
Personal Website