Wednesday, October 31, 2012
Tuesday, October 30, 2012
Draw Route between two point on google map in android
Call below RetreiveFeedTask.class like this..
String url = "http://routes.cloudmade.com/A6421860EBB04234AB5EF2D049F2CD8F/api/0.3/"
+ mLatitude_Current+ ","
+ mLongitude_Current+","
+ mLatitude_Place+ ","
+ mLongitude_Place + "/car.gpx";
new RetreiveFeedTask(ActivityMapDrawPath.this, MapView, MapView.getOverlays(), mGeoPoint_Current).execute(url);
RetreiveFeedTask.class
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.AsyncTask;
import android.widget.Toast;
import androidexperts.app.gujrattourism.parser.ParserRouteDetails;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class RetreiveFeedTask extends AsyncTask
private ProgressDialog dialog;
Activity mActivity;
ArrayList
public ParserRouteDetails mXMLGetterSetter;
MapView mMapView;
List
MapOverlay mapOverlay;
GeoPoint mGeoPoint_Current;
public RetreiveFeedTask(Activity mActivity,MapView mMapView,List
this.mActivity = mActivity;
this.mMapView = mMapView;
this.mListOverlay = mListOverlay;
this.mGeoPoint_Current = mGeoPoint_Current;
dialog = new ProgressDialog(mActivity);
}
protected Void doInBackground(String... urls) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XMLParserHandler myXMLHandler = new XMLParserHandler();
xr.setContentHandler(myXMLHandler);
URL url = new URL(urls[0]);
itemsList = myXMLHandler.getItemsArrayList();
xr.parse(new InputSource(url.openStream()));
return null;
} catch (Exception e) {
return null;
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Loading...");
this.dialog.show();
}
protected void onPostExecute(Void feed) {
mMapView.invalidate();
if (dialog.isShowing())
dialog.dismiss();
if(itemsList.size() > 0){
mapOverlay = new MapOverlay(mGeoPoint_Current);
mListOverlay.add(mapOverlay);
}else{
Toast.makeText(mActivity, "Path not Found......", Toast.LENGTH_SHORT).show();
}
}
public class MapOverlay extends com.google.android.maps.Overlay {
int check_id;
public MapOverlay(GeoPoint mGeoPoint) {
}
@Override
public boolean draw(final Canvas canvas, MapView mapView, boolean shadow, long when) {
Point mpoint = new Point();
Point mpoint1 = new Point();
GeoPoint firstGeoPoint = null;
GeoPoint secondGeoPoint = null;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// if(itemsList.size() > 0){
for (int i = 0; i < itemsList.size(); i++) {
mXMLGetterSetter = itemsList.get(i);
if (i < (itemsList.size() - 1)) {
firstGeoPoint = new GeoPoint(
(int)(Double.parseDouble(itemsList.get(i).getLatitude())*1E6),
(int)(Double.parseDouble(itemsList.get(i).getLongitude())*1E6));
secondGeoPoint = new GeoPoint(
(int)(Double.parseDouble(itemsList.get(i+1).getLatitude())*1E6),
(int)(Double.parseDouble(itemsList.get(i+1).getLongitude())*1E6));
paint.setDither(true);
paint.setColor(Color.parseColor("#562302"));
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(100);
paint.setStrokeCap(Paint.Cap.ROUND);
Path path = new Path();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(7f);
mapView.getProjection().toPixels(firstGeoPoint, mpoint);
mapView.getProjection().toPixels(secondGeoPoint, mpoint1);
path.moveTo(mpoint1.x, mpoint1.y);
path.lineTo(mpoint.x, mpoint.y);
canvas.drawPath(path, paint);
}
}
// }else{
// Toast.makeText(mActivity, "Path not Found......", Toast.LENGTH_SHORT).show();
// }
return false;
}
}
}
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();
}
}
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);
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 keyboardfor focus on EditTextimm.showSoftInput(ed, 0);
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();
}
}
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;
}
{
ActivityManager am= (ActivityManager)
mContext.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList
rti=(ArrayList
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;
}
{
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;
}
{
ConnectivityManager mConnectivityManager =
(ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager
.getActiveNetworkInfo();
if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
return true;
else
return false;
}
Subscribe to:
Posts (Atom)