Monday, October 29, 2012

Get Angle from using SensorManager In Android

private float[] mGravity;
    private float[] mMagnetic;
  
    private float getDirection()
    {
      
        float[] temp = new float[9];
        float[] R = new float[9];
        //Load rotation matrix into R
        SensorManager.getRotationMatrix(temp, null,
                mGravity, mMagnetic);
      
        //Remap to camera's point-of-view
        SensorManager.remapCoordinateSystem(temp,
                SensorManager.AXIS_X,
                SensorManager.AXIS_Z, R);
      
        //Return the orientation values
        float[] values = new float[3];
        SensorManager.getOrientation(R, values);
      
        //Convert to degrees
        for (int i=0; i < values.length; i++) {
            Double degrees = (values[i] * 180) / Math.PI;
            values[i] = degrees.floatValue();
        }

        return values[0];
      
    }
  
    @Override
    public void onSensorChanged(SensorEvent event) {
        switch(event.sensor.getType()) {
              
        case Sensor.TYPE_ACCELEROMETER:
            mGravity = event.values.clone();
            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            mMagnetic = event.values.clone();
            break;
        default:
            return;
        }
        if(mGravity != null && mMagnetic != null) {
            getDirection();
        }
    }

Friday, October 26, 2012

Play audio file (.mp3) from asset folder in android.

import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

public class AudioPlayer {
  
    String fileName;
    Context contex;
    MediaPlayer mp;

    //Constructor
    public AudioPlayer(String name, Context context) {
        fileName = name;
        contex = context;
        playAudio();
    }

    //Play Audio
    public void playAudio() {
        mp = new MediaPlayer();
        try {
            AssetFileDescriptor descriptor = contex.getAssets()
                    .openFd(fileName);
            mp.setDataSource(descriptor.getFileDescriptor(),
                    descriptor.getStartOffset(), descriptor.getLength());
            descriptor.close();
            mp.prepare();
            mp.setLooping(true);
            mp.start();
            mp.setVolume(3, 3);

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Stop Audio
    public void stop() {
        mp.stop();
    }
}


Call this class from any activity like as new AudioPlayer(file_name, mContext);

Programatically Hide/Show Android Soft Keyboard

InputMethodManager imm = (InputMethodManager)getSystemService(Service.INPUT_METHOD_SERVICE);
for hide keyboard
 imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); 
for show keyboard
 imm.showSoftInput(ed, 0);
for focus on EditText
 ed.requestFocus();

Changes in Menifest.xml

<activity android:name=".Activity" android:configChanges="keyboard|orientation"></activity>
 
 For more information check this Question

Monday, October 22, 2012

Set Map Center according to multiple GeoPoint (Display all pin on screen))

public static void setCenterGeoPoint(GeoPoint[] mGeoPoint ,
                                                              MapController mapController)
{
        GeoPoint mGeoPointCenter;
        int maxLatitude = 0;
        int minLatitude = 0;
        int maxLongitude = 0;
        int minLongitude = 0;
      
        try {
            if(mGeoPoint.length!=0)
            {
                for (GeoPoint item : mGeoPoint)
                { // item Contain list of Geopints
                    int lat = item.getLatitudeE6();
                    int lon = item.getLongitudeE6();

                    maxLatitude = Math.max(lat, maxLatitude);
                    minLatitude = Math.min(lat, minLatitude);
                    maxLongitude = Math.max(lon, maxLongitude);
                    minLongitude = Math.min(lon, minLongitude);
                }
            }
          

            mapController.zoomToSpan(Math.abs(maxLatitude - minLatitude)/2,
                    Math.abs(maxLongitude - minLongitude)/2);

            mGeoPointCenter = new GeoPoint(
                    (maxLatitude + minLatitude) ,(maxLongitude + minLongitude));

            mapController.animateTo(mGeoPointCenter);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

Check Application is running in front ?

public static boolean isApplicationInFront(Context mContext)
{
        ActivityManager  am= (ActivityManager)
             mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList rti = new ArrayList();
        rti=(ArrayList)am.getRunningTasks(2);
        String currenact = rti.get(0).topActivity.getPackageName().toString();
      
        if(currenact.equals(mContext.getPackageName().toString()))
            return true;
      
        return false;
}

Calculate Distance between two location (GeoPoint)

public double CalculationByDistance(Location Start, Location End)
{
        double Radius = 6371;
        double lat1 = Start.getLatitude();
        double lat2 = End.getLatitude();
        double lon1 = Start.getLongitude();
        double lon2 = End.getLongitude();
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
                * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double km = Radius * c;
        return km * 1000;
}

Check Internet is Available in Android Device

public boolean check_Internet(Context mContext)
{
        ConnectivityManager mConnectivityManager =
                  (ConnectivityManager) mContext
                               .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo mNetworkInfo =  mConnectivityManager
                                                            .getActiveNetworkInfo();

        if (mNetworkInfo != null &&  mNetworkInfo.isConnectedOrConnecting())
            return true;
        else
            return false;
}