Android - Utils

From XennisWiki
Jump to: navigation, search

Helpful utils for developing Android apps.

Network

NetworkUtil.java

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

public class NetworkUtil {

	/**
	 * Determine if you have an internet connection.
	 * 
	 * @see <a href="http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html">connectivity-monitoring.html</a>
	 * 
	 * @param context
	 *            Android context
	 * @return True, if is connected or connects
	 */
	public static boolean isConnectedToInternet(Context context) {
		NetworkInfo activeNetwork = getNetworkInfo(context);
		return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
	}

	/**
	 * Determine if the internect connection is a of type WIFI.
	 * 
	 * @param context
	 *            Android context
	 * @return True, if it a WIFI connection
	 */
	public static boolean isConnectedToWiFi(Context context) {
		if (isConnectedToInternet(context)) {
			return getNetworkInfo(context).getType() == ConnectivityManager.TYPE_WIFI;
		} else {
			return false;
		}
	}

	/**
	 * Get network information.
	 * 
	 * @param context
	 *            Android context
	 * @return Returns details about the currently active default data network,
	 *         see
	 *         {@link android.net.ConnectivityManager#getActiveNetworkInfo()}
	 */
	private static NetworkInfo getNetworkInfo(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		return cm.getActiveNetworkInfo();
	}
}

Storage

StorageUtil.java

import java.io.FileNotFoundException;
import java.io.OutputStreamWriter;

import android.content.Context;
import android.os.Environment;

public class StorageUtil {
	
	/**
	 * Checks if external storage is available for read and write
	 * 
	 * @return True, if external storage is writable
	 */
	public static boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		return Environment.MEDIA_MOUNTED.equals(state);
	}

	/**
	 * Checks if external storage is available to at least read
	 * 
	 * @return True, if external storage is at least readable
	 */
	public static boolean isExternalStorageReadable() {
		String state = Environment.getExternalStorageState();
		return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
	}
	
	/**
	 * (Creates and) opens a file in the Context's application package and
	 * returns a output stream writer.
	 * 
	 * @param context
	 *            Android context
	 * @param filename
	 *            File name (without path)
	 * @return Output stream writer for the given file
	 * @throws FileNotFoundException
	 */
	public static OutputStreamWriter getOutputStreamWrite(Context context, String filename) throws FileNotFoundException {
		return new OutputStreamWriter(context.openFileOutput(filename, Context.MODE_PRIVATE));
	}

}

Location

LocationManager.java without continuous location update

import android.app.Activity;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;

public class LocationManager implements
		GooglePlayServicesClient.ConnectionCallbacks,
		GooglePlayServicesClient.OnConnectionFailedListener {

	private static final String LOG = LocationManager.class.getName();
	
	/**
	 * Define a request code to send to Google Play services
	 * This code is returned in Activity.onActivityResult
	 */
	public final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

	/** Stores the current instantiation of the location client in this object */
	private LocationClient mLocationClient;	

	private Activity activity;
    
	public LocationManager(Activity activity) {
		this.activity = activity;
		mLocationClient = new LocationClient(activity, this, this);
	}	

	public void onStart() {
		/*
        	 * Connect the client. Don't re-start any requests here;
        	 * instead, wait for onResume()
        	 */
        	mLocationClient.connect();
	}
	
	public void onStop() {
        	// After disconnect() is called, the client is considered "dead".
        	mLocationClient.disconnect();
	}	
	
	/**
	 * Verify that Google Play services is available before making a request.
	 *
	 * @return true if Google Play services is available, otherwise false
	 */
	private boolean servicesConnected() {
        	// Check that Google Play services is available
        	int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);

        	// If Google Play services is available
        	if (ConnectionResult.SUCCESS == resultCode) {
        		Log.d(LOG, "Google Play services is available.");
            		return true;
        	}
        	// Google Play services was not available for some reason        
        	else {
           	 Log.d(LOG, "Google Play services is not available, resultCode=" + resultCode);
            	return false;
		}
	}	

	/*
	 * Called by Location Services when the request to connect the
	 * client finishes successfully. At this point, you can
	 * request the current location or start periodic updates
	 */
	@Override
	public void onConnected(Bundle dataBundle) {
		Log.d(LOG, "Connected");
	}

	/*
	 * Called by Location Services if the connection to the
	 * location client drops because of an error.
	 */    
	@Override
	public void onDisconnected() {
   	 	Log.d(LOG, "Disconnected. Please re-connect.");		
	}
    
	/*
	 * Called by Location Services if the attempt to
	 * Location Services fails.
	 */
	@Override
	public void onConnectionFailed(ConnectionResult connectionResult) {
		/*
		 * Google Play services can resolve some errors it detects.
		 * If the error has a resolution, try sending an Intent to
		 * start a Google Play services activity that can resolve
		 * error.
		 */
		if (connectionResult.hasResolution()) {
			try {
                		// Start an Activity that tries to resolve the error
                		connectionResult.startResolutionForResult(
                        		activity,
                        		CONNECTION_FAILURE_RESOLUTION_REQUEST);
			/*
                	 * Thrown if Google Play services canceled the original
                	 * PendingIntent
                 	 */
            		} catch (IntentSender.SendIntentException e) {
                		// Log the error
            			Log.d(LOG, e.getMessage());
       			}
        	} else {
       			// If no resolution is available, log the error.
        		Log.d(LOG, "Error code: " + connectionResult.getErrorCode());
        	}
		
	}
	
	/**
	 * Calls
	 * {@link com.google.android.gms.location.LocationClient#getLastLocation()
	 * getLastLocation()} to get the current location
	 * 
	 * @return last location
	 * @throws NoLocationException
	 *             Get thrown, when no location is available
	 */
    	public Location getLastLocation() throws NoLocationException {
    		if (servicesConnected() && mLocationClient.isConnected()) {
    			Log.d(LOG, "service and client are connected");
    			Location lastLocation = mLocationClient.getLastLocation();
    			if (lastLocation != null) {
    				return lastLocation;
    			}
    		}
    		throw new NoLocationException();
    	}
    
}

NoLocationException.java

public class NoLocationException extends Exception {

	private static final long serialVersionUID = 1L;

	public NoLocationException() {
		super("Unable to find location. Turn on location access.");
	}
}

Device

DeviceUtil.java

import android.content.Context;
import android.content.res.Configuration;
import android.webkit.WebSettings;

public class DeviceUtil {

	/**
	 * Checks the screen size to detect a tablet.
	 * 
	 * @return true If the screen is equal or greater then
	 *         <code>Configuration.SCREENLAYOUT_SIZE_LARGE</code>
	 */
	public static boolean isTablet(Context context) {
		/*
		 * Or use SCREENLAYOUT_SIZE_XLARGE;
		 */
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}
	
	/**
	 * Activate HTML5 cache for a {@link android.webkit.WebView WebView}.
	 * 
	 * @see <a
	 *      href="http://alex.tapmania.org/2010/11/html5-cache-android-webview.html">html5-cache-android-webview.html</a>
	 * 
	 * @param context
	 *            Android context
	 * @param webSettings
	 *            The web settings of the WebView
	 */
	@SuppressWarnings("deprecation")
	public static void activateHTMLCache(Context context, WebSettings webSettings) {
        webSettings.setDomStorageEnabled(true);

	      // Set cache size to 8 mb by default. should be more than enough
        webSettings.setAppCacheMaxSize(1024*1024*8);
	       
	      // It's the DEFAULT location for your app's cache
        webSettings.setAppCachePath(context.getCacheDir().getAbsolutePath());
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        mapWebView.setWebViewClient(new WebChromeClient() {
//            @Override
//            public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,
//                         WebStorage.QuotaUpdater quotaUpdater)
//            {
//                  quotaUpdater.updateQuota(spaceNeeded * 2);
//            }
//        });
	}

}

See also