Background Service is crashing on "start service" - android

I have to find the location of user such that , that even when I close the app it continues in the background. The code working fine and it's displaying correct locations but when I click "Start Service" It crashes. I can't find the mistake:
GPS TRACKING CLASS
package com.malay.gpsservice;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class GPSTracService extends Service implements LocationListener {
// DECLARE ALL THE VARIABLES
Location location = null; // location
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled=false;
String msg = "CAUTION! If kept open, can consume lots of battery";
// FOR FOREGROUND_ID
int FORE_ID = 1335;
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("NewApi")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Intent noty_intent = new Intent(this,
com.malay.gpsservice.MainActivity.class);
noty_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, noty_intent,
0);
Notification n = new Notification.Builder(this)
.setContentTitle("GPS Serice is running...")
.setContentText(msg).setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).setAutoCancel(true).setOngoing(true)
.build();
startForeground(FORE_ID, n);
try {
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// First get location from Network Provider
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network","Network");
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if (!isGPSEnabled) {
} else {
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Toast.makeText(this,
"Location Listener on GPS started...",
Toast.LENGTH_SHORT).show();
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception ex) {
Toast.makeText(this,
"Some Error occur while starting Location Listener",
Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
return (START_STICKY);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
if (locationManager != null) {
locationManager.removeUpdates((LocationListener) this);
locationManager = null;
}
stopForeground(true);
Toast.makeText(this, "Location Listener on GPS Stopped...",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
here is the main activity:
package com.malay.gpsservice;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener{
Context mcontext=this;
boolean isGpsEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
protected LocationManager locManager;
Location loc=null;
double latitude;
double longitude;
double accuracy;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE=20;
private static final long MIN_TIME_BETWEEN_UPDATE=1000*60;
double latitudet;
double longitudet;
double accuracyt;
TextView tview;
TextView tlat;
TextView tlon;
TextView tacc;
String lat;
String lon;
String acc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loc=getLocation();
tview = (TextView) findViewById(R.id.textView1);
try {
getGPSLoc();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
//Refresh Button
if (item.getItemId() == R.id.ref) {
getLocation();
getGPSLoc();
}
return super.onMenuItemSelected(featureId, item);
}
public void getGPSLoc() {
if (latitude != 0.0 && longitude != 0.0) {
tview.setText("Location Fixed");
} else {
tview.setText("Waiting for Location...");
}
if (canGetLocation) {
latitudet=(double)Math.round(latitude*1000000)/1000000;
tlat = (TextView) findViewById(R.id.lat);
lat = Double.toString(latitudet);
tlat.setText(lat);
longitudet=(double)Math.round(longitude*1000000)/1000000;
tlon = (TextView) findViewById(R.id.lon);
lon = Double.toString(longitudet);
tlon.setText(lon);
accuracyt=(double)Math.round(accuracy*100)/100;
tacc = (TextView) findViewById(R.id.acc);
acc = Double.toString(accuracyt);
tacc.setText(acc);
}
}
public Location getLocation(){
try{
locManager=(LocationManager)mcontext.getSystemService(LOCATION_SERVICE);
isGpsEnabled=locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGpsEnabled || isNetworkEnabled){
this.canGetLocation=true;
// First get location from Network Provider
if(isNetworkEnabled){
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BETWEEN_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, (LocationListener) this);
Log.d("Network","Network");
if(locManager!=null){
loc=locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
accuracy=loc.getAccuracy();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if(isGpsEnabled){
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BETWEEN_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, (LocationListener) this);
Log.d("GPS Enabled","GPS Enabled");
if(locManager!=null){
loc=locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc!=null){
latitude=loc.getLatitude();
longitude=loc.getLongitude();
accuracy=loc.getAccuracy();
}
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
return loc;
}
public void startServ(View vw){
Intent gps=new Intent(this,GPSTracService.class);
this.startService(gps);
}
public void stopServ(View vw){
Intent gps=new Intent(this,GPSTracService.class);
this.stopService(gps);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.malay.gpsservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.malay.gpsservice.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".GPSTracService" />
</application>
</manifest>
Logcat

Use getApplicationContext() instead of this in service.
Changed below line.
Intent noty_intent = new Intent(getApplicationContext(), com.malay.gpsservice.MainActivity.class);
.
.
Notification n = new Notification.Builder(getApplicationContext())
instead of
Intent noty_intent = new Intent(this, com.malay.gpsservice.MainActivity.class);
Note : must declare service in menifest.xml if it missing.
Update :
Use below code for Notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setStyle(new NotificationCompat.BigTextStyle().bigText("App Name"))
.setContentText("App Name");
startForeground(1, mBuilder.build());
Use android.support.v7 library and set Target Version 21

Related

get Latitude Longitude fail

I have two question with my code
can not enter the onLocationChanged() function
mylocation is always null
I also add the permission and turn on my device GPS function
<uses-permission android:name ="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name ="android.permission.ACCESS_COARSE_LOCATION"/>
follows is my code please help me to get Latitude Lontitude thanks all.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Getaddress getaddress = new Getaddress();
getaddress.excute();
}
public class Getaddress implements LocationListener {
Geocoder geocoder;
private Location mylocation;
private double Latitude;
private double Lontitude;
private LocationManager locationManager;
public Getaddress() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
mylocation = locationManager.getLastKnownLocation(provider);
Boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.w("isGPSEnabled",isGPSEnabled.toString());
}
public void excute()
{
Latitude = mylocation.getLatitude();
Lontitude = mylocation.getLongitude();
Toast.makeText(SecondActivity.this, "Latitude"+Double.toString(Latitude),Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location)
{
mylocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Xml File :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/str_tv_location"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_location"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_longitude"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Java file:
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager ;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting LocationManager object
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Permission :-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
At first: you need GPS available space.
Secondly: your location is always null, because your space for GRP LOCATION not available. You need to check if GPS working or not
onLocationChanged method work every time when your location changed.
public class GPSTracker implements LocationListener {
public GPSTracker(Context con){
LocationManager lm = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// do something here...
//location.getLatitude();
//location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Internet Permission for Location Updates

Do I really need Internet Permission to get the current Location through either GPS or Network Provider.
I run the below code without giving Internet Permission .It is working fine.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.practice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.practice.LocationActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.practice.AlarmReceiver" >
</receiver>
</application>
</manifest>
LocationService.java
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
public class LocationService implements LocationListener {
private final Context mContext;
private boolean isGPSEnabled = false;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location location;
private double latitude;
private double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public LocationService(Context context) {
this.mContext = context;
location = getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("network ", isNetworkEnabled+"");
Log.i("GPS ", isGPSEnabled+"");
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
canGetLocation = true;
if (isGPSEnabled) {
if (locationManager != null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("GPS", "GPS");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isNetworkEnabled) {
Log.i("location", location+"");
if (location == null) {
Log.i("Location Manager", locationManager+"");
if (locationManager != null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("NETWORK", "NETWORK");
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public boolean canGetLocation() {
return canGetLocation;
}
public void onLocationChanged(Location location) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
LocationActivity.java
package com.example.practice;
import com.example.location.LocationService;
import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class LocationActivity extends Activity {
LocationService locationService;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
button=(Button)findViewById(R.id.btn_location);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationService=new LocationService(LocationActivity.this);
if(locationService.canGetLocation())
{
Location location=locationService.getLocation();
Toast.makeText(LocationActivity.this, location.getLatitude()+ " "+location.getLongitude(),Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.location, menu);
return true;
}
}
Yes it will work as you added the location permission and also see this on developers site http://developer.android.com/training/location/retrieve-current.html

Determining the speed of a vehicle using GPS in android

I would like to know how to get the speed of a vehicle using your phone while seated in the vehicle using gps. I have read that the accelerometer is not very accurate. Another thing is; will GPS be accessible while seated in a vehicle. Won't it have the same effect as while you are in a building?
Here is some code I have tried but I have used the NETWORK PROVIDER instead.I will appreciate the help. Thanks...
package com.example.speedtest;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
LocationManager locManager;
LocationListener li;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
li=new speed();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, li);
}
class speed implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
Float thespeed=loc.getSpeed();
Toast.makeText(MainActivity.this,String.valueOf(thespeed), Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}
}
for more information onCalculate Speed from GPS Location Change in Android Mobile Device view this link
Mainly there are two ways to calculate the speed from mobile phone.
Calculate speed from Accelerometer
Calculate speed from GPS Technology
Unlike Accelerometer from GPS Technology if you're going to calculate speed you must enable data connection and GPS connection.
In here we are going to calculate speed using GPS connection.
In this method we using how frequency the GPS Location points are changing during single time period. Then if we have the real distance between the geo locations points we can get the speed. Because we have the distance and the time.
Speed = distance/time
But getting the distance between two location points is not very easy. Because the world is a goal in shape the distance between two geo points is different from place to place and angle to angle. So we have to use “Haversine Algorithm”
First we have to give permission for Get Location data in Manifest file
Make the GUI
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txtCurrentSpeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="000.0 miles/hour"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox android:id="#+id/chkMetricUnits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Use metric units?"/>
Then make an interface to get the speed
package com.isuru.speedometer;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public interface IBaseGpsListener extends LocationListener, GpsStatus.Listener {
public void onLocationChanged(Location location);
public void onProviderDisabled(String provider);
public void onProviderEnabled(String provider);
public void onStatusChanged(String provider, int status, Bundle extras);
public void onGpsStatusChanged(int event);
}
Implement the logic to get the speed using the GPS Location
import android.location.Location;
public class CLocation extends Location {
private boolean bUseMetricUnits = false;
public CLocation(Location location)
{
this(location, true);
}
public CLocation(Location location, boolean bUseMetricUnits) {
// TODO Auto-generated constructor stub
super(location);
this.bUseMetricUnits = bUseMetricUnits;
}
public boolean getUseMetricUnits()
{
return this.bUseMetricUnits;
}
public void setUseMetricunits(boolean bUseMetricUntis)
{
this.bUseMetricUnits = bUseMetricUntis;
}
#Override
public float distanceTo(Location dest) {
// TODO Auto-generated method stub
float nDistance = super.distanceTo(dest);
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nDistance = nDistance * 3.28083989501312f;
}
return nDistance;
}
#Override
public float getAccuracy() {
// TODO Auto-generated method stub
float nAccuracy = super.getAccuracy();
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nAccuracy = nAccuracy * 3.28083989501312f;
}
return nAccuracy;
}
#Override
public double getAltitude() {
// TODO Auto-generated method stub
double nAltitude = super.getAltitude();
if(!this.getUseMetricUnits())
{
//Convert meters to feet
nAltitude = nAltitude * 3.28083989501312d;
}
return nAltitude;
}
#Override
public float getSpeed() {
// TODO Auto-generated method stub
float nSpeed = super.getSpeed() * 3.6f;
if(!this.getUseMetricUnits())
{
//Convert meters/second to miles/hour
nSpeed = nSpeed * 2.2369362920544f/3.6f;
}
return nSpeed;
}
}
Combine logic to GUI
import java.util.Formatter;
import java.util.Locale;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity implements IBaseGpsListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.updateSpeed(null);
CheckBox chkUseMetricUntis = (CheckBox) this.findViewById(R.id.chkMetricUnits);
chkUseMetricUntis.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
MainActivity.this.updateSpeed(null);
}
});
}
public void finish()
{
super.finish();
System.exit(0);
}
private void updateSpeed(CLocation location) {
// TODO Auto-generated method stub
float nCurrentSpeed = 0;
if(location != null)
{
location.setUseMetricunits(this.useMetricUnits());
nCurrentSpeed = location.getSpeed();
}
Formatter fmt = new Formatter(new StringBuilder());
fmt.format(Locale.US, "%5.1f", nCurrentSpeed);
String strCurrentSpeed = fmt.toString();
strCurrentSpeed = strCurrentSpeed.replace(' ', '0');
String strUnits = "miles/hour";
if(this.useMetricUnits())
{
strUnits = "meters/second";
}
TextView txtCurrentSpeed = (TextView) this.findViewById(R.id.txtCurrentSpeed);
txtCurrentSpeed.setText(strCurrentSpeed + " " + strUnits);
}
private boolean useMetricUnits() {
// TODO Auto-generated method stub
CheckBox chkUseMetricUnits = (CheckBox) this.findViewById(R.id.chkMetricUnits);
return chkUseMetricUnits.isChecked();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
CLocation myLocation = new CLocation(location, this.useMetricUnits());
this.updateSpeed(myLocation);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onGpsStatusChanged(int event) {
// TODO Auto-generated method stub
}
}
If you want to convert Meters/Second to kmph-1 then you need to multipl the Meters/Second answer from 3.6
Speed from kmph-1 = 3.6 * (Speed from ms-1)
GPS works fine in a vehicle. The NETWORK_PROVIDER setting might not be accurate enough to get a reliable speed, and the locations from the NETWORK_PROVIDER may not even contain a speed. You can check that with location.hasSpeed() (location.getSpeed() will always return 0).
If you find that location.getSpeed() isn't accurate enough, or it is unstable (i.e. fluctuates drastically) then you can calculate speed yourself by taking the average distance between a few GPS locations and divide by the time elapsed.
public class MainActivity extends Activity implements LocationListener {
add implements LocationListener next to Activity
LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
LocationManager.GPS_PROVIDER, 0, 0, The first zero stands for minTime and the second one for minDistance in which you update your values. Zero means basically instant updates which can be bad for battery life, so you may want to adjust it.
#Override
public void onLocationChanged(Location location) {
if (location==null){
// if you can't get speed because reasons :)
yourTextView.setText("00 km/h");
}
else{
//int speed=(int) ((location.getSpeed()) is the standard which returns meters per second. In this example i converted it to kilometers per hour
int speed=(int) ((location.getSpeed()*3600)/1000);
yourTextView.setText(speed+" km/h");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
}
Don't forget the Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
We can use location.getSpeed();
try {
// Get the location manager
double lat;
double lon;
double speed = 0;
LocationManager locationManager = (LocationManager)
getActivity().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
lat = location.getLatitude();
lon = location.getLongitude();
speed =location.getSpeed();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
mTxt_lat.setText("" + lat);
mTxt_speed.setText("" + speed);
}catch (Exception ex){
ex.printStackTrace();
}

Gps Notification Icon Not Blinking

i am trying google maps api on my android phone via following code. My app locating my phone and working great but gps notification icon not blinking. How can i blink gps icon when locating my phone.
Thanks For Replies.
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And The Code :
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.EditText;
import android.widget.Toast;
public class main extends MapActivity {
MapController mControl;
GeoPoint geoP;
MapView mapV;
MyLocationOverlay compass;
EditText etext;
String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etext = (EditText) findViewById(R.id.latLong);
mapV = (MapView) findViewById(R.id.mapView);
mapV.displayZoomControls(true);
mapV.setBuiltInZoomControls(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enable) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = location.getLatitude() * 1E6;
Double longi = location.getLongitude() * 1E6;
geoP = new GeoPoint(lat.intValue(), longi.intValue());
List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
compass = new MyLocationOverlay(this, mapV);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoP, "Hola, Mundo!","I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapV.getOverlays().add(compass);
mapOverlays.add(itemizedoverlay);
mControl = mapV.getController();
mControl.animateTo(geoP);
mControl.setZoom(5);
mControl.setCenter(geoP);
locationManager.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
public void onStatusChanged(String provider, int status,
Bundle extras) {
if (status == LocationProvider.AVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.AVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.OUT_OF_SERVICE",
Toast.LENGTH_SHORT).show();
}
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(),
"Location Changed", Toast.LENGTH_SHORT).show();
}
});
//etext.setText(String.valueOf(lat) + "," + String.valueOf(longi));
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
compass.disableCompass();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
compass.enableCompass();
}
protected boolean isRouteDisplayed() {
return false;
}
t0mm13b, working on my handset but GPS notification icon not blinking. Virtual Device means Emulator. I solved problem.
Code :
package com.yunusoksuz.gmapstest;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class YnsmapsActivity extends Activity implements LocationListener {
/** Called when the activity is first created. */
private LocationManager locationManager;
private Location location;
private String provider;
private Double lat, longi;
private Criteria criteria;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
public void onLocationChanged(Location location) {
Toast.makeText(
this,
"Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();
tv.setText("Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude());
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
Now gps notification blinking.

application has stopped unexpectedly in android emulator

I am looking for the optimized way to get user's location and I found the sample example here, which was answered by Mr. Fedor on on Jun 30 '10
I did the same way as he explained in his code, the only difference is that I am using the gotLocation callback method of abstract class result. In this method I am tring to show the Provider name as a msg using Toast.makeText. When I run this code, nothing get displayed on my emulator and after few seconds it show the message "Application has stopped unexpectedly android emulator". I increase the time, which was set in the timer1.schedule method, but no luck.
I am just stating development in android platform, so I don't have enough knowledge about the same, so can anybody help me to resolve this issue.
Below is my code
file Name: UserLocation.java
package com.ideafarms.android.mylocation;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class UserLocation{
Timer timer1;
LocationManager locMgr;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerNetwork);
}
};
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
timer1.cancel();
locationResult.gotLocation(location);
locMgr.removeUpdates(this);
locMgr.removeUpdates(locationListenerGps);
}
};
public boolean getLocation(Context context, LocationResult result){
// Use LocationResult callback class to pass location value from UserLocation to User code
locationResult = result;
if(locMgr == null){
locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Handle exception if provider is not permitted
try{
gps_enabled = locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled = locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
// don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled){
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
return true;
}
class GetLastLocation extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
locMgr.removeUpdates(locationListenerGps);
locMgr.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled){
gps_loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(network_enabled){
net_loc=locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
// if there are both values use the latest one
if(gps_loc!=null && net_loc!= null){
if(gps_loc.getTime()>net_loc.getTime()){
locationResult.gotLocation(gps_loc);
}else{
locationResult.gotLocation(net_loc);
}
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
and
package com.ideafarms.android.mylocation;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.ideafarms.android.mylocation.UserLocation.LocationResult;
public class MyLocation extends Activity {
/** Called when the activity is first created. */
TextView myLoc ;
public LocationResult locResult = new LocationResult(){
#Override
*public void gotLocation(Location location) {
// TODO Auto-generated method stub
Toast msg = Toast.makeText(MyLocation.this, location.getProvider(), Toast.LENGTH_LONG);
//msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}*
};
boolean loc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
UserLocation usrLocation = new UserLocation();
myLoc = (TextView)findViewById(R.id.myLocation);
loc = usrLocation.getLocation(this, locResult);
}
}
I have marked the code in italic where I am having problem.
Thanks
Take a look here: http://developer.android.com/guide/developing/tools/emulator.html
You need to emulate an gps device in order to get location data from the emulator.

Categories

Resources