Android Tutorial - Core Class : Context

 Context.MODE_WORLD_READABLE

//package ch.racic.android.linuxtag2009.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

class AppUtil {
    /**
     * Show a level
     * 
     * @param context The context
     * @param level The level
     */
    public static void showLevel( Context context, int level)
    {
        String filename= "gelaendeplan.png";
        File f = new File( context.getFilesDir() + "/" + filename);
        try {
            if( f.exists() == false) {
                InputStream is = context.getAssets().open( filename);
                FileOutputStream fos = context.openFileOutput( filename, Context.MODE_WORLD_READABLE);
                byte[] buffer = new byte[is.available()];
                is.read(buffer);
                // write the stream to file
                fos.write(buffer, 0, buffer.length);
                fos.close();
                is.close();
            }

            // Prepare the intent
            Intent intent = new Intent( Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(f), "image/png");
            context.startActivity(intent);
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }
}

Returns whether the context is running on the android emulator.

//package eu.MrSnowflake.android.snowutils;

import android.content.Context;
import android.telephony.TelephonyManager;

class SnowUtils {
  public static final String EMULATOR_IMEI = "000000000000000";
  
  /**
   * Returns whether the context is running on the android emulator. 
   * @param ctx The calling context.
   * @return True: Running on emulator. False: Running on a real device
   */
  public static boolean isEmulator(Context ctx) {
    TelephonyManager telephonyMgr = (TelephonyManager)ctx.getSystemService(Context.TELEPHONY_SERVICE);        
    //to be deleted in final
    // always use simulator when in emulator 
    return !telephonyMgr.getDeviceId().equals(EMULATOR_IMEI);
  }
}

check Internet for Context

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

class Main {
  public static boolean checkInternet(Context ctx) {
    NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
        .getSystemService(Context.CONNECTIVITY_SERVICE))
        .getActiveNetworkInfo();

    if (info == null || !info.isConnected())
      return false;
    if (info.isRoaming())
      return false;
    return true;
  }
}

add Link

//package de.rothbayern.android.ac.misc;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.util.Linkify;
import android.widget.TextView;

class Util {
  public static void addLink(Context pContext, TextView voteView,
      int linkMarkerId, int urlId) {
    String patS = pContext.getResources().getString(linkMarkerId);
    Pattern pat = Pattern.compile(patS);
    String scheme = pContext.getResources().getString(urlId);
    Linkify.addLinks(voteView, pat, scheme, null,
        new Linkify.TransformFilter() {

          public String transformUrl(Matcher matcher, String url) {
            return "";
          }

        });
  }

}

performing common form field validation tasks

     
package mobilesmil.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class FormValidationUtils {
  
  public static final String INTEGER_REGEX = "\\d+";
  public static final char[] INVALID_FILENAME_CHARS = new char[]{
    '\\','/','?','\"','\'','<','>',':','*','|','\t','\n','\r'
  };
  

  public static AlertDialog createInvalidFormDialog(Context context) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
      dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
        dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            return; // button simply closes the dialog
          } });
        return dialogBuilder.create();
  }
}

Reads all text from asset with specified path.

     
//package ru.kvolkov.myreader.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import android.content.Context;
import android.util.Log;

class AssetsHelper {
  private static final String TAG = "AssetsHelper";
  private static final int BUFFER_SIZE = 65536;

  private Context m_context;


  public AssetsHelper(Context context) {
    m_context = context;
  }

  public String readAllText(String assetPath) {
    InputStream stream = null;
    try {
      stream = m_context.getAssets().open(assetPath);
      return readAllText(stream);
    } catch (IOException e) {
      Log.e(TAG, "Error on asset reading.", e);
    } finally {
      closeStream(stream);
    }
    return "";
  }

  private static String readAllText(InputStream stream) throws IOException {
    Reader reader = new InputStreamReader(stream);

    final char[] buffer = new char[BUFFER_SIZE];
    StringBuilder result = new StringBuilder();
    int read;
    while (true) {
      read = reader.read(buffer, 0, BUFFER_SIZE);
      if (read > 0) {
        result.append(buffer, 0, read);
        continue;
      }
      return result.toString();
    }
  }

  private static void closeStream(InputStream stream) {
    if (stream != null) {
      try {
        stream.close();
      } catch (IOException e) {
        Log.e(TAG, "Error on asset reading.", e);
      }
    }
  }
}

Context Delete File

    
import android.content.Context;

class Common {
  public static void DeleteFile(Context context, String fileName) {
    context.deleteFile(fileName);
  }
}

Context Open file

    
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;

class Common {
  public static String ReadFileData(Context context, String fileName) {

    String strValue = null;

    File file = context.getFileStreamPath(fileName);
    if (file.exists()) {
      StringBuilder sb = new StringBuilder();
      BufferedReader bufferReader = null;
      try {
        // ?????????????buffer??
        bufferReader = new BufferedReader(new InputStreamReader(
            context.openFileInput(fileName)));
        String strLine = null;
        while ((strLine = bufferReader.readLine()) != null) {
          sb.append(strLine);
        }

      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          bufferReader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      strValue = sb.toString();
    }

    return strValue;
  }
}

Context.openFileOutput

    
import java.io.IOException;
import java.io.OutputStreamWriter;

import android.content.Context;

class Common {
  public static boolean WriteToFile(Context context, String strContent, String fileName) {
    boolean bReturn = true;
    OutputStreamWriter osw = null;

    try {
      // ??????
      osw = new OutputStreamWriter(context.openFileOutput(fileName, context.MODE_PRIVATE));
      osw.write(strContent);
      osw.flush();
    } catch (Exception e) {
      e.printStackTrace();
      bReturn = false;
    } finally {
      try {
        osw.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return bReturn;
  }
}